import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Param,
  Body,
  HttpException,
  HttpStatus,
  Req,
  Query,
} from '@nestjs/common';
import { JobPostsService } from './job_posts.service';
import { JobPosts } from './entities/job_posts.entity';
import { Public } from '../auth/public.decorator';
import {
  ApiBearerAuth,
  ApiTags,
  ApiBody,
  ApiParam,
  ApiQuery,
  ApiOperation,
} from '@nestjs/swagger';

@ApiTags('job_posts')
@ApiBearerAuth('access-token')
@Controller('job_posts')
export class JobPostsController {
  constructor(private readonly jobPostsService: JobPostsService) {}

  // GET /job_posts/featured
  @Public()
  @Get('featured')
  @ApiOperation({ summary: 'Get featured jobs' })
  async findFeaturedJobs() {
    try {
      return await this.jobPostsService.findFeaturedJobs();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch featured jobs',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
  // GET /jobs/applications?status=pending&page=1&limit=10&search=keyword
  @Public()
  @Get('applications')
  @ApiOperation({ summary: 'Get Job Applications' })
  @ApiQuery({ name: 'status', required: false, type: String })
  @ApiQuery({ name: 'page', required: false, type: String })
  @ApiQuery({ name: 'limit', required: false, type: String })
  @ApiQuery({ name: 'search', required: false, type: String })
  async getJobApplications(
    @Query('status') status?: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
    @Query('search') search?: string,
  ) {
    const pageNumber = page ? parseInt(page, 10) : 1;
    const limitNumber = limit ? parseInt(limit, 10) : 10;

    return this.jobPostsService.getApplications(
      status,
      pageNumber,
      limitNumber,
      search,
    );
  }

  @Public()
  @Get('stats/active')
  @ApiOperation({ summary: 'Get active job stats' })
  async getActiveJobStats() {
    return this.jobPostsService.getActiveJobStats();
  }
  // PUT /jobs/applications/:id/approve
  @Public()
  @Put('applications/:id/approve')
  @ApiOperation({ summary: 'Approve Job Application' })
  @ApiParam({ name: 'id', type: Number })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        adminId: { type: 'number', example: 1 },
        remarks: { type: 'string', example: 'Approved for interview' },
      },
      required: ['adminId'],
    },
  })
  async approveJob(
    @Param('id') id: number,
    @Body() body: { adminId: number; remarks?: string },
  ) {
    return this.jobPostsService.updateStatus(
      id,
      'open',
      body.adminId,
      body.remarks,
    );
  }
  // PUT /jobs/applications/:id/reject
  @Public()
  @Put('applications/:id/reject')
  @ApiOperation({ summary: 'Reject Job Application' })
  @ApiParam({ name: 'id', type: Number })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        adminId: { type: 'number', example: 1 },
        remarks: { type: 'string', example: 'Not qualified' },
      },
      required: ['adminId'],
    },
  })
  async rejectJob(
    @Param('id') id: number,
    @Body() body: { adminId: number; remarks?: string },
  ) {
    return this.jobPostsService.updateStatus(
      id,
      'rejected',
      body.adminId,
      body.remarks,
    );
  }

  // PUT /jobs/applications/:id/status
  @Public()
  @Put('applications/:id/status')
  @ApiOperation({ summary: 'Update Job Application Status' })
  @ApiParam({ name: 'id', type: Number })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        status: { type: 'string', example: 'shortlisted' },
        adminId: { type: 'number', example: 1 },
        remarks: { type: 'string', example: 'Good candidate' },
      },
      required: ['status', 'adminId'],
    },
  })
  async updateJobStatus(
    @Param('id') id: number,
    @Body() body: { status: string; adminId: number; remarks?: string },
  ) {
    return this.jobPostsService.updateJobStatus(
      id,
      body.status,
      body.adminId,
      body.remarks,
    );
  }

  // PUT /jobs/applications/mass-approve
  @Public()
  @Put('applications/mass-approve')
  @ApiOperation({ summary: 'Mass Approve Pending Applications' })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        adminId: { type: 'number', example: 1 },
        remarks: { type: 'string', example: 'Mass approval' },
      },
      required: ['adminId'],
    },
  })
  async massApprovePending(
    @Body() body: { adminId: number; remarks?: string },
  ) {
    return this.jobPostsService.massApprovePending(body.adminId, body.remarks);
  }

  // Basic CRUD endpoints

  @Get()
  @ApiOperation({ summary: 'Get all job posts' })
  async findAll(): Promise<JobPosts[]> {
    try {
      return await this.jobPostsService.findAll();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch job posts',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
  @Public()
  @Get('search')
  @ApiOperation({ summary: 'Search jobs' })
  @ApiQuery({ name: 'query', type: Object, required: false })
  async searchJobs(@Query() query: Record<string, any>) {
    if (!query || Object.keys(query).length === 0) {
      throw new HttpException(
        'Search query is required',
        HttpStatus.BAD_REQUEST,
      );
    }
    return this.jobPostsService.searchJobs(query);
  }
  @Public()
  @Get('by_role/:roleId')
  @ApiOperation({ summary: 'Find jobs by role' })
  @ApiParam({ name: 'roleId', type: Number })
  async findByRole(@Param('roleId') roleId: number) {
    if (!roleId) {
      throw new HttpException('Role ID is required', HttpStatus.BAD_REQUEST);
    }
    return this.jobPostsService.findByRole(+roleId);
  }

  @Public()
  @Get(':jobId/related')
  @ApiOperation({ summary: 'Get related jobs' })
  @ApiParam({ name: 'jobId', type: Number })
  @ApiQuery({ name: 'limit', type: Number, required: false })
  @ApiQuery({ name: 'page', type: Number, required: false })
  @ApiQuery({ name: 'clearCache', type: Boolean, required: false })
  async getRelatedJobs(
    @Param('jobId') jobId: number,
    @Query('limit') limit: number = 6,
    @Query('page') page: number = 1,
    @Query('clearCache') clearCache: boolean = false,
  ) {
    if (!jobId) {
      throw new HttpException('Job ID is required', HttpStatus.BAD_REQUEST);
    }
    return this.jobPostsService.getRelatedJobs(
      +jobId,
      +limit,
      +page,
      clearCache,
    );
  }

  @Public()
  @Get(':jobId/tags')
  @ApiOperation({ summary: 'Get tags for job' })
  @ApiParam({ name: 'jobId', type: Number })
  async getTagsForJob(@Param('jobId') jobId: number) {
    if (!jobId) {
      throw new HttpException('Job ID is required', HttpStatus.BAD_REQUEST);
    }
    return this.jobPostsService.getTagsForJob(+jobId);
  }

  // NEW: Server-side filtered jobs endpoint - MUST come before @Get(':id')
  @Public()
  @Get('filtered')
  @ApiOperation({ summary: 'Filter Jobs' })
  @ApiQuery({ name: 'search', required: false })
  @ApiQuery({
    name: 'experience',
    required: false,
    description: 'Experience Level ID or Name',
  })
  @ApiQuery({ name: 'salary', required: false, description: 'Format: min-max' })
  @ApiQuery({ name: 'city', required: false })
  @ApiQuery({ name: 'state', required: false })
  @ApiQuery({ name: 'country', required: false })
  @ApiQuery({
    name: 'jobFreshness',
    required: false,
    description: 'Days since posted (e.g. 7)',
  })
  @ApiQuery({
    name: 'jobType',
    required: false,
    description: 'Job Type Name (e.g. Full Time)',
  })
  @ApiQuery({
    name: 'education',
    required: false,
    description: 'Education Level ID or Name',
  })
  @ApiQuery({
    name: 'jobLevel',
    required: false,
    description: 'Job Level Name',
  })
  @ApiQuery({ name: 'fresher', required: false, type: Boolean })
  @ApiQuery({ name: 'jobsForWomen', required: false, type: Boolean })
  @ApiQuery({ name: 'nightShift', required: false, type: Boolean })
  @ApiQuery({
    name: 'industry',
    required: false,
    description: 'Industry ID or Name',
  })
  @ApiQuery({
    name: 'roleLevel',
    required: false,
    description: 'Role Level ID',
  })
  @ApiQuery({ name: 'skill', required: false, description: 'Skill ID or Name' })
  @ApiQuery({ name: 'role', required: false, description: 'Role ID' })
  @ApiQuery({
    name: 'userId',
    required: false,
    description: 'User ID for bookmark status',
  })
  @ApiQuery({ name: 'page', required: false, example: 1 })
  @ApiQuery({ name: 'limit', required: false, example: 10 })
  async findFilteredJobs(
    @Query('search') search?: string,
    @Query('experience') experience?: string,
    @Query('salary') salary?: string,
    @Query('city') city?: string,
    @Query('state') state?: string,
    @Query('country') country?: string,
    @Query('jobFreshness') jobFreshness?: string,
    @Query('jobType') jobType?: string,
    @Query('education') education?: string,
    @Query('jobLevel') jobLevel?: string,
    @Query('fresher') fresher?: string,
    @Query('jobsForWomen') jobsForWomen?: string,
    @Query('nightShift') nightShift?: string,
    @Query('industry') industry?: string,
    @Query('roleLevel') roleLevel?: string,
    @Query('skill') skill?: string,
    @Query('role') role?: string,
    @Query('userId') userId?: string,
    @Query('page') page: string = '1',
    @Query('limit') limit: string = '10',
  ): Promise<{
    data: any[];
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  }> {
    return this.jobPostsService.findFilteredJobs({
      search,
      experience,
      salary,
      city,
      state,
      country,
      jobFreshness,
      jobType,
      skill,
      education,
      jobLevel,
      fresher: fresher === 'true',
      jobsForWomen: jobsForWomen === 'true',
      nightShift: nightShift === 'true',
      industry,
      roleLevel: roleLevel ? Number(roleLevel) : undefined,
      role: role ? Number(role) : undefined,
      userId: userId ? Number(userId) : undefined,
      page: Number(page),
      limit: Number(limit),
    });
  }

  // NEW: Get job filter options - MUST come before @Get(':id')
  @Public()
  @Get('filter_options')
  @ApiOperation({ summary: 'Get job filter options' })
  async getJobFilterOptions(): Promise<any> {
    return this.jobPostsService.getJobFilterOptions();
  }

  // GET /job_posts/directory_links
  @Public()
  @Get('directory_links')
  @ApiOperation({ summary: 'Get directory links for footer' })
  async getDirectoryLinks() {
    try {
      return await this.jobPostsService.getDirectoryLinks();
    } catch (error) {
      console.error('Error in getDirectoryLinks controller:', error);
      throw new HttpException(
        `Failed to fetch directory links: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get job post by id' })
  @ApiParam({ name: 'id', type: Number })
  async findOne(@Param('id') id: number): Promise<JobPosts> {
    if (!id) {
      throw new HttpException('Id is required', HttpStatus.BAD_REQUEST);
    }
    try {
      return await this.jobPostsService.findOne(+id);
    } catch (error) {
      throw new HttpException(
        error.message || 'Job post not found',
        error.status || HttpStatus.NOT_FOUND,
      );
    }
  }

  // ============================================================================
  // COMMENTED OUT: This endpoint is NOT used by the frontend
  // Frontend uses: POST /job_posts/create_with_user instead (see line 734)
  // This endpoint requires authentication via @Req() req which is less flexible
  // Keeping it commented to avoid developer confusion
  // ============================================================================
  // @Public()
  // @Post()
  // @ApiOperation({ summary: 'Create job post' })
  // @ApiBody({
  //   schema: {
  //     type: 'object',
  //     properties: {
  //       title: { type: 'string', example: 'Senior React Developer' },
  //       description: { type: 'string' },
  //       requirements: { type: 'string' },
  //       benefits: { type: 'string' },
  //       company_id: { type: 'number' },
  //       role_id: { type: 'number' },
  //       role_levels_id: { type: 'number' },
  //       country_id: { type: 'number' },
  //       state_id: { type: 'number' },
  //       city_id: { type: 'number' },
  //       pincode: { type: 'string' },
  //       area_id: { type: 'number' },
  //       job_type_id: { type: 'number' },
  //       experience_id: { type: 'number' },
  //       education_id: { type: 'number' },
  //       industry_id: { type: 'number' },
  //       salary_min: { type: 'number' },
  //       salary_max: { type: 'number' },
  //       vacancies: { type: 'number' },
  //       urgent_hiring: { type: 'boolean' },
  //       shift: { type: 'string', enum: ['day', 'night', 'flexible'] },
  //       gender: { type: 'string', enum: ['male', 'female', 'any'] },
  //       english_level: { type: 'string' },

  //       // Walk-in Interview
  //       walk_in_interview: { type: 'string', enum: ['yes', 'no'] },
  //       walkin_address: { type: 'string' },
  //       walkin_start_date: { type: 'string', format: 'date' },
  //       walkin_end_date: { type: 'string', format: 'date' },
  //       walkin_start_time: { type: 'string' },
  //       walkin_end_time: { type: 'string' },
  //       walkin_instructions: { type: 'string' },

  //       // Communication
  //       communication_preference: { type: 'string', enum: ['email', 'whatsapp', 'phone'] },
  //       other_recruiter_name: { type: 'string' },
  //       other_recruiter_whatsapp: { type: 'string' },
  //       other_recruiter_email: { type: 'string' },
  //       notification_preference: { type: 'string' },

  //       // AI Interview
  //       ai_interview_enabled: { type: 'boolean' },
  //       ai_interview_duration: { type: 'number' },
  //       ai_window_days: { type: 'number' },
  //       ai_question_count: { type: 'number' },
  //       ai_difficulty: { type: 'string' },
  //       ai_experience_level: { type: 'number' },
  //       ai_config: { type: 'object' },
  //       ai_schedule_requires_approval: { type: 'boolean' },

  //       // Arrays
  //       skills: { type: 'array', items: { type: 'string' }, description: 'Array of skill names or IDs' },
  //       tags: { type: 'array', items: { type: 'string' } },
  //       perks: { type: 'array', items: { type: 'number' }, description: 'IDs of selected perks' },
  //       customPerks: { type: 'array', items: { type: 'string' } }
  //     },
  //     required: ['title', 'description', 'role_id', 'country_id', 'state_id', 'city_id']
  //   }
  // })
  // async create(@Req() req, @Body() data: Partial<JobPosts>) {

  //   if (req.user.activeRole === 'company' || req.user.activeRole === 'recruiter') {
  //     // If company_id is provided, verify ownership
  //     let companyId = data.company_id;
  //     if (!companyId) {
  //       companyId = await this.jobPostsService.getCompanyIdForUser(req.user.id);
  //       if (!companyId) {
  //         throw new HttpException(
  //           'No company found for this user',
  //           HttpStatus.BAD_REQUEST,
  //         );
  //       }
  //       data.company_id = companyId;
  //     } else {
  //       // Double-check: does this company_id belong to the logged-in user?
  //       const userCompanyId = await this.jobPostsService.getCompanyIdForUser(
  //         req.user.id,
  //       );
  //       if (companyId !== userCompanyId) {
  //         throw new HttpException(
  //           'Invalid company_id for this user',
  //           HttpStatus.FORBIDDEN,
  //         );
  //       }
  //     }
  //   } else if (req.user.activeRole === 'admin') {
  //     if (!data.company_id) {
  //       throw new HttpException(
  //         'Admin must specify company_id',
  //         HttpStatus.BAD_REQUEST,
  //       );
  //     }
  //   } else {
  //     throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
  //   }
  //   return await this.jobPostsService.createjob(data);
  // }

  @Public()
  @Put(':id')
  @ApiOperation({ summary: 'Update job post' })
  @ApiParam({ name: 'id', type: Number })
  @ApiBody({
    schema: {
      type: 'object',
      description: 'Update Job Post',
      properties: {
        title: { type: 'string' },
        description: { type: 'string' },
        status: { type: 'string', enum: ['open', 'closed', 'paused'] },
        requirements: { type: 'string' },
        benefits: { type: 'string' },
        company_id: { type: 'number' },
        role_id: { type: 'number' },
        role_levels_id: { type: 'number' },
        country_id: { type: 'number' },
        state_id: { type: 'number' },
        city_id: { type: 'number' },
        pincode: { type: 'string' },
        area_id: { type: 'number' },
        job_type_id: { type: 'number' },
        experience_id: { type: 'number' },
        education_id: { type: 'number' },
        industry_id: { type: 'number' },
        salary_min: { type: 'number' },
        salary_max: { type: 'number' },
        vacancies: { type: 'number' },
        urgent_hiring: { type: 'boolean' },
        shift: { type: 'string', enum: ['day', 'night', 'flexible'] },
        gender: { type: 'string', enum: ['male', 'female', 'any'] },
        english_level: { type: 'string' },

        // Walk-in Interview
        walk_in_interview: { type: 'string', enum: ['yes', 'no'] },
        walkin_address: { type: 'string' },
        walkin_start_date: { type: 'string', format: 'date' },
        walkin_end_date: { type: 'string', format: 'date' },
        walkin_start_time: { type: 'string' },
        walkin_end_time: { type: 'string' },
        walkin_instructions: { type: 'string' },

        // Communication
        communication_preference: {
          type: 'string',
          enum: ['email', 'whatsapp', 'phone'],
        },
        other_recruiter_name: { type: 'string' },
        other_recruiter_whatsapp: { type: 'string' },
        other_recruiter_email: { type: 'string' },
        notification_preference: { type: 'string' },

        // Collections
        skills: { type: 'array', items: { type: 'string' } },
        tags: { type: 'array', items: { type: 'string' } },
        perks: { type: 'array', items: { type: 'number' } },
        custom_perks: { type: 'array', items: { type: 'string' } },

        // AI Interview Updates
        ai_interview_enabled: { type: 'boolean' },
        ai_interview_duration: { type: 'number' },
        ai_window_days: { type: 'number' },
        ai_question_count: { type: 'number' },
        ai_difficulty: { type: 'string' },
        ai_experience_level: { type: 'number' },
        ai_config: { type: 'object' },
        ai_schedule_requires_approval: { type: 'boolean' },
      },
    },
  })
  async update(
    @Param('id') id: number,
    @Body() data: Partial<JobPosts>,
  ): Promise<JobPosts> {
    try {
      return await this.jobPostsService.update(+id, data);
    } catch (error) {
      throw new HttpException(
        error.message || 'Failed to update job post',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Delete job post' })
  @ApiParam({ name: 'id', type: Number })
  async remove(@Param('id') id: number): Promise<{ message: string }> {
    try {
      return await this.jobPostsService.remove(+id);
    } catch (error) {
      throw new HttpException(
        error.message || 'Failed to delete job post',
        HttpStatus.BAD_REQUEST,
      );
    }
  }

  // --- NEW: Endpoints for job posts with joined details ---

  // GET /job_posts/details
  @Public()
  @Get('details/all')
  @ApiOperation({ summary: 'Get all job posts with details' })
  async findAllWithDetails() {
    try {
      return await this.jobPostsService.findAllWithDetails();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch job posts with details',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // GET /job_posts/details/:id
  @Public()
  @Get('details/:id')
  @ApiOperation({ summary: 'Get job post with details by id' })
  @ApiParam({ name: 'id', type: Number })
  async findOneWithDetails(
    @Param('id') id: number,
    @Query('userId') userId?: string,
  ) {
    if (!id) {
      throw new HttpException('Id is required', HttpStatus.BAD_REQUEST);
    }
    try {
      return await this.jobPostsService.findOneWithDetails(
        +id,
        userId ? +userId : undefined,
      );
    } catch (error) {
      throw new HttpException(
        error.message || 'Job post not found',
        error.status || HttpStatus.NOT_FOUND,
      );
    }
  }

  // GET /job_posts/by_role_level/:roleLevelId
  @Public()
  @Get('by_role_level/:roleLevelId')
  @ApiOperation({ summary: 'Find jobs by role level' })
  @ApiParam({ name: 'roleLevelId', type: Number })
  async findByRoleLevel(@Param('roleLevelId') roleLevelId: number) {
    if (!roleLevelId) {
      throw new HttpException(
        'Role Level ID is required',
        HttpStatus.BAD_REQUEST,
      );
    }
    try {
      return await this.jobPostsService.findByRoleLevel(+roleLevelId);
    } catch (error) {
      throw new HttpException(
        error.message || 'Failed to fetch job posts by role level',
        error.status || HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // GET /job_posts/details/:id/expiry-status
  @Public()
  @Get('details/:id/expiry-status')
  @ApiOperation({ summary: 'Check job expiry status' })
  @ApiParam({ name: 'id', type: Number })
  async checkExpiry(@Param('id') id: number) {
    if (!id) throw new HttpException('Id is required', HttpStatus.BAD_REQUEST);
    const job = await this.jobPostsService.getExpiryStatus(+id);
    if (job.isExpired) {
      throw new HttpException('Job expired', HttpStatus.GONE);
    }
    return { status: 'active' };
  }

  // ___ NEW: Endpoints for frontend dropdown options ___

  // GET /job_posts/options/categories
  // @Public()
  // @Get('options/categories')
  // async getJobCategories() {
  //   try {
  //     return await this.jobPostsService.getJobCategories();
  //   } catch (error) {
  //     throw new HttpException(
  //       'Failed to fetch job categories',
  //       HttpStatus.INTERNAL_SERVER_ERROR,
  //     );
  //   }
  // }

  // GET /job_posts/options/locations
  @Public()
  @Get('options/locations')
  @ApiOperation({ summary: 'Get location options' })
  async getLocations() {
    try {
      return await this.jobPostsService.getLocations();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch locations',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // GET /job_posts/options/job_types
  @Public()
  @Get('options/job_types')
  @ApiOperation({ summary: 'Get job type options' })
  async getJobTypes() {
    try {
      return await this.jobPostsService.getJobTypes();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch job types',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // GET /job_posts/options/job_types_with_counts
  @Public()
  @Get('options/job_types_with_counts')
  @ApiOperation({ summary: 'Get job type options with counts' })
  async getJobTypesWithCounts() {
    try {
      return await this.jobPostsService.getJobTypesWithCounts();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch job types with counts',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // GET /job_posts/options/experience_levels
  @Public()
  @Get('options/experience_levels')
  @ApiOperation({ summary: 'Get experience level options' })
  async getExperienceLevels() {
    try {
      return await this.jobPostsService.getExperienceLevels();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch experience levels',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // GET /job_posts/options/education_levels_with_counts
  @Public()
  @Get('options/education_levels_with_counts')
  @ApiOperation({ summary: 'Get education level options with counts' })
  async getEducationLevelsWithCounts() {
    try {
      return await this.jobPostsService.getEducationLevelsWithCounts();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch education levels with counts',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // GET /job_posts/options/education_levels
  @Public()
  @Get('options/education_levels')
  @ApiOperation({ summary: 'Get education level options' })
  async getEducationLevels() {
    try {
      return await this.jobPostsService.getEducationLevels();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch education levels',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // GET /job_posts/mega_menu/education_levels
  @Public()
  @Get('mega_menu/education_levels')
  @ApiOperation({ summary: 'Get mega menu education levels' })
  async getMegaMenuEducationLevels() {
    try {
      // console.log('Fetching mega menu education levels...');
      const result = await this.jobPostsService.getMegaMenuEducationLevels();
      // console.log('Mega menu education levels result:', result);
      return result;
    } catch (error) {
      console.error('Error in getMegaMenuEducationLevels controller:', error);
      throw new HttpException(
        `Failed to fetch mega menu education levels: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // GET /job_posts/mega_menu/industries
  @Public()
  @Get('mega_menu/industries')
  @ApiOperation({ summary: 'Get mega menu industries' })
  async getMegaMenuIndustries() {
    try {
      // console.log('Fetching mega menu industries...');
      const result = await this.jobPostsService.getMegaMenuIndustries();
      // console.log('Mega menu industries result:', result);
      return result;
    } catch (error) {
      console.error('Error in getMegaMenuIndustries controller:', error);
      throw new HttpException(
        `Failed to fetch mega menu industries: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }



  // GET /job_posts/options/role_levels
  @Public()
  @Get('options/role_levels')
  @ApiOperation({ summary: 'Get role level options' })
  async getRoleLevels() {
    try {
      return await this.jobPostsService.getRoleLevels();
    } catch (error) {
      throw new HttpException(
        'Failed to fetch role levels',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  @Public()
  @Post('create_with_user')
  @ApiOperation({ summary: 'Create Job with User ID' })
  @ApiBody({
    schema: {
      type: 'object',
      description: 'Create Job for User (Recruiter/Associate)',
      properties: {
        userId: { type: 'number', description: 'Target User ID' },
        company_id: { type: 'number', description: 'Required for Associates' },
        role: { type: 'string', description: 'Role Name (if role_id not set)' },
        role_definition: { type: 'string' },

        // Standard Job Fields
        title: { type: 'string' },
        address: { type: 'string' },
        description: { type: 'string' },
        requirements: { type: 'string' },
        benefits: { type: 'string' },
        desirable: { type: 'string' },
        role_id: { type: 'number' },
        role_levels_id: { type: 'number' },
        country_id: { type: 'number' },
        state_id: { type: 'number' },
        city_id: { type: 'number' },
        pincode: { type: 'string' },
        area_id: { type: 'number' },
        job_type_id: { type: 'number' },
        job_level_id: { type: 'number' },
        experience_id: { type: 'number' },
        education_id: { type: 'number' },
        industry_id: { type: 'number' },
        salary_min: { type: 'number' },
        salary_max: { type: 'number' },
        vacancies: { type: 'number' },
        urgent_hiring: { type: 'boolean' },
        featured: { type: 'boolean' },
        status: {
          type: 'string',
          enum: ['pending', 'open', 'closed', 'draft'],
        },
        image_url: { type: 'string' },
        expires_at: { type: 'string', format: 'date' },
        shift: { type: 'string', enum: ['day', 'night', 'flexible'] },
        gender: { type: 'string', enum: ['male', 'female', 'any'] },
        english_level: { type: 'string' },

        // Walk-in Interview
        walk_in_interview: { type: 'string', enum: ['yes', 'no'] },
        walkin_address: { type: 'string' },
        walkin_start_date: { type: 'string', format: 'date' },
        walkin_end_date: { type: 'string', format: 'date' },
        walkin_start_time: { type: 'string' },
        walkin_end_time: { type: 'string' },
        walkin_instructions: { type: 'string' },

        // Communication
        communication_preference: {
          type: 'string',
          enum: ['email', 'whatsapp', 'phone'],
        },
        other_recruiter_name: { type: 'string' },
        other_recruiter_whatsapp: { type: 'string' },
        other_recruiter_email: { type: 'string' },
        notification_preference: { type: 'string' },

        // AI Interview
        ai_interview_enabled: { type: 'boolean' },
        ai_interview_duration: { type: 'number' },
        ai_window_days: { type: 'number' },
        ai_question_count: { type: 'number' },
        ai_difficulty: { type: 'string' },
        ai_experience_level: { type: 'number' },
        ai_config: { type: 'object' },
        ai_schedule_requires_approval: { type: 'boolean' },
        ai_start_time: { type: 'string' },
        ai_end_time: { type: 'string' },
        ai_question_set_id: { type: 'number' },
        ai_validity_days: { type: 'number' },
        ai_generation_timing: { type: 'string' },

        // Collections
        skills: { type: 'array', items: { type: 'string' } },
        tags: { type: 'array', items: { type: 'string' } },
        perks: { type: 'array', items: { type: 'number' } },
        customPerks: { type: 'array', items: { type: 'string' } },
      },
      required: ['userId', 'title', 'city_id'],
    },
  })
  async createWithUserId(@Body() data: any) {
    return this.jobPostsService.createWithUserId(data);
  }
}
