import { Controller, Get, Query, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { Public } from '../../modules/auth/public.decorator';
import { DashboardService } from '../../modules/dashboard/dashboard.service';
import { RoleLevelsService } from '../../modules/role_levels/role_levels.service';
import { CompaniesService } from '../../modules/companies/companies.service';

@ApiTags('mobile_home')
@Controller('mobile/home')
export class MobileHomeController {
  private readonly logger = new Logger(MobileHomeController.name);

  constructor(
    private readonly dashboardService: DashboardService,
    private readonly roleLevelsService: RoleLevelsService,
    private readonly companiesService: CompaniesService,
  ) {}

  @Public()
  @Get()
  @ApiOperation({ summary: 'Get aggregated home page data for mobile app' })
  @ApiQuery({
    name: 'userId',
    required: false,
    type: Number,
    description: 'User ID (required for logged-in users)',
  })
  @ApiQuery({
    name: 'role',
    required: false,
    type: String,
    description: 'User role: seeker or recruiter',
  })
  async getMobileHomeData(
    @Query('userId') userId?: number,
    @Query('role') role?: string,
  ) {
    this.logger.log(`Mobile home request - userId: ${userId}, role: ${role}`);

    // Initialize response structure
    const response = {
      success: true,
      overview: null as any,
      profile_completion: null as any,
      job_alert: null as any,
      explore_jobs: [] as any[],
      top_companies: [] as any[],
    };

    // Track if all sections failed
    let allSectionsFailed = true;

    // 1. Profile Completion (only for seeker role)
    if (role === 'seeker' && userId) {
      try {
        const profileData =
          await this.dashboardService.getSeekerProfileCompletion(userId);

        if (profileData && profileData.success) {
          response.profile_completion = {
            percentage: profileData.completion || 0,
            missing_sections: profileData.missingFields || [],
          };
          allSectionsFailed = false;
        } else {
          this.logger.warn(
            `Profile completion returned unsuccessful for userId: ${userId}`,
          );
          response.profile_completion = null;
        }
      } catch (error: any) {
        this.logger.error(
          `Failed to fetch profile completion for userId ${userId}:`,
          error.message,
        );
        response.profile_completion = null;
      }
    } else {
      // Not a seeker or no userId - profile completion not applicable
      response.profile_completion = null;
    }

    // 2. Job Alert Summary (only for seeker role)
    if (role === 'seeker' && userId) {
      try {
        const jobAlertData =
          await this.dashboardService.getJobAlertsjoblistForSeeker(userId, {
            page: 1,
            limit: 1,
          });

        if (jobAlertData && jobAlertData.success) {
          response.job_alert = {
            enabled: true,
            new_jobs_count: jobAlertData.data?.pagination?.total || 0,
          };
          allSectionsFailed = false;
        } else {
          this.logger.warn(
            `Job alert returned unsuccessful for userId: ${userId}`,
          );
          response.job_alert = null;
        }
      } catch (error: any) {
        this.logger.error(
          `Failed to fetch job alert for userId ${userId}:`,
          error.message,
        );
        response.job_alert = null;
      }
    } else {
      // Not a seeker or no userId - job alert not applicable
      response.job_alert = null;
    }

    // 2.1 Seeker Overview (only for seeker role)
    if (role === 'seeker' && userId) {
      try {
        const overviewData = await this.dashboardService.getSeekerOverview(
          userId.toString(),
        );

        if (overviewData && overviewData.success) {
          response.overview = overviewData.data;

          // Should not break if profile completion is already fetched above
          if (response.profile_completion?.percentage) {
            // Optional: inject profile completion into overview if strict adherence to mockup is needed,
            // but 'reuse service response structure' suggests keeping it as is from service.
            // We will stick to the service response structure as per instructions.
          }
          allSectionsFailed = false;
        } else {
          this.logger.warn(
            `Seeker overview returned unsuccessful for userId: ${userId}`,
          );
          response.overview = null;
        }
      } catch (error: any) {
        this.logger.error(
          `Failed to fetch seeker overview for userId ${userId}:`,
          error.message,
        );
        response.overview = null;
      }
    } else {
      response.overview = null;
    }

    // 3. Explore Jobs (role levels with counts)
    try {
      const roleLevelsData =
        await this.roleLevelsService.getRoleLevelsWithCounts();

      if (Array.isArray(roleLevelsData)) {
        response.explore_jobs = roleLevelsData.map((item) => ({
          id: item.id,
          name: item.name,
          job_count: parseInt(item.job_count) || 0,
        }));
        allSectionsFailed = false;
      } else {
        this.logger.warn('Role levels data is not an array');
        response.explore_jobs = [];
      }
    } catch (error: any) {
      this.logger.error(
        'Failed to fetch role levels with counts:',
        error.message,
      );
      response.explore_jobs = [];
    }

    // 4. Top Companies (companies with open positions)
    try {
      const companiesData =
        await this.companiesService.findAllWithOpenPositions();

      if (Array.isArray(companiesData)) {
        response.top_companies = companiesData.map((company) => ({
          company_id: company.id,
          company_name: company.name,
          location: company.location || null,
          logo: company.logo || null,
          featured: company.featured || 0,
          open_positions: parseInt(company.positions) || 0,
        }));
        allSectionsFailed = false;
      } else {
        this.logger.warn('Companies data is not an array');
        response.top_companies = [];
      }
    } catch (error: any) {
      this.logger.error(
        'Failed to fetch companies with open positions:',
        error.message,
      );
      response.top_companies = [];
    }

    // If all sections failed, mark success as false
    if (allSectionsFailed) {
      response.success = false;
      this.logger.error('All mobile home sections failed to load');
    }

    return response;
  }
}
