import {
  Controller,
  Post,
  Body,
  Get,
  Query,
  UseGuards,
  Request,
  Res,
  Header,
} from '@nestjs/common';
import { Response } from 'express';
import { ProfileUnlockService } from './profile_unlock.service';
import { Public } from '../auth/public.decorator';

@Controller('profile-unlock')
export class ProfileUnlockController {
  constructor(private readonly profileUnlockService: ProfileUnlockService) {}

  @Public()
  @Get('check')
  async checkAccess(
    @Query('recruiterUserId') recruiterUserId: string,
    @Query('seekerUserId') seekerUserId: string,
    @Query('actionType') actionType?: string,
  ) {
    const isUnlocked = await this.profileUnlockService.isProfileUnlocked(
      Number(recruiterUserId),
      Number(seekerUserId),
      actionType,
    );
    return { unlocked: isUnlocked };
  }

  @Public()
  @Get('list')
  async getUnlockedCandidates(
    @Query('recruiterUserId') recruiterUserId: string,
    @Query('page') page: number = 1,
    @Query('limit') limit: number = 10,
    @Query('jobId') jobId?: string,
  ) {
    try {
      return await this.profileUnlockService.getUnlockedCandidates(
        Number(recruiterUserId),
        page,
        limit,
        jobId ? Number(jobId) : undefined,
      );
    } catch (error) {
      return {
        success: false,
        message: error.message || 'Failed to fetch unlocked candidates',
      };
    }
  }

  @Public()
  @Post('unlock')
  async unlockProfile(
    @Body()
    body: {
      recruiterUserId: number;
      seekerUserId: number;
      action?: string;
    },
  ) {
    try {
      return await this.profileUnlockService.unlockProfile(
        body.recruiterUserId,
        body.seekerUserId,
        body.action,
      );
    } catch (error) {
      return {
        success: false,
        message: error.message || 'Failed to unlock profile',
      };
    }
  }

  @Public()
  @Post('export')
  @Header(
    'Content-Type',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  )
  @Header(
    'Content-Disposition',
    'attachment; filename="unlocked_candidates.xlsx"',
  )
  async exportUnlockedCandidates(
    @Body() body: { recruiterUserId: number; jobId?: number },
    @Res() res: Response,
  ) {
    try {
      const buffer = await this.profileUnlockService.exportToExcel(
        body.recruiterUserId,
        body.jobId,
      );

      res.set({
        'Content-Type':
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'Content-Disposition':
          'attachment; filename="unlocked_candidates.xlsx"',
        'Content-Length': buffer.length,
      });

      res.end(buffer);
    } catch (error) {
      res.status(400).json({
        success: false,
        message: error.message || 'Failed to export candidates',
      });
    }
  }
}
