import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFile,
  Body,
  Get,
  Put,
  Delete,
  Param,
  Req,
  UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import { BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SeekerResume } from './entities/seeker_resumes.entity';
import { SeekerResumesService } from './seeker_resumes.service';
import {
  ApiBearerAuth,
  ApiTags,
  ApiOperation,
  ApiConsumes,
  ApiBody,
  ApiQuery,
} from '@nestjs/swagger';
import { Public } from '../auth/public.decorator';

@ApiTags('seeker_resumes')
@ApiBearerAuth('access-token')
@Controller('seeker_resumes')
export class SeekerResumesController {
  constructor(
    private readonly seekerResumesService: SeekerResumesService
  ) {}

  @UseGuards(JwtAuthGuard)
  @Post('upload')
  @ApiOperation({ summary: 'Upload resume' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        resume: {
          type: 'string',
          format: 'binary',
        },
        seeker_id: {
          type: 'number',
        },
      },
    },
  })
  @UseInterceptors(
    FileInterceptor('resume', {
      storage: diskStorage({
        destination: './uploads/resumes',
        filename: (req, file, cb) => {
          const uniqueSuffix =
            Date.now() + '-' + Math.round(Math.random() * 1e9);
          cb(null, uniqueSuffix + extname(file.originalname));
        },
      }),
      limits: { fileSize: 5 * 1024 * 1024 },
      fileFilter: (req, file, cb) => {
        if (!file.originalname.match(/\.(pdf|doc|docx)$/)) {
          return cb(new BadRequestException('Only pdf, doc, or docx files are allowed!'), false);
        }
        cb(null, true);
      },
    }),
  )
  async uploadResume(
    @Req() req: any,
    @UploadedFile() file: Express.Multer.File,
  ) {
    const userId = req.user?.id || req.user?.userId || req.user?.sub;
    return this.seekerResumesService.uploadResume(userId, file);
  }

  @UseGuards(JwtAuthGuard)
  @Get()
  @ApiOperation({ summary: 'Get resumes for authenticated user' })
  async getResumes(@Req() req: any) {
    const userId = req.user?.id || req.user?.userId || req.user?.sub;
    const resumes = await this.seekerResumesService.getResumes(userId);
    return { resumes };
  }

  @UseGuards(JwtAuthGuard)
  @Delete(':id')
  @ApiOperation({ summary: 'Delete a resume' })
  async deleteResume(@Req() req: any, @Param('id') id: number) {
    const userId = req.user?.id || req.user?.userId || req.user?.sub;
    return this.seekerResumesService.deleteResume(userId, id);
  }

  @UseGuards(JwtAuthGuard)
  @Put(':id/replace')
  @ApiOperation({ summary: 'Replace an existing resume' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        resume: { type: 'string', format: 'binary' },
      },
    },
  })
  @UseInterceptors(
    FileInterceptor('resume', {
      storage: diskStorage({
        destination: './uploads/resumes',
        filename: (req, file, cb) => {
          const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
          cb(null, uniqueSuffix + extname(file.originalname));
        },
      }),
      limits: { fileSize: 5 * 1024 * 1024 },
      fileFilter: (req, file, cb) => {
        if (!file.originalname.match(/\.(pdf|doc|docx)$/)) {
          return cb(new BadRequestException('Only pdf, doc, or docx files are allowed!'), false);
        }
        cb(null, true);
      },
    }),
  )
  async replaceResume(
    @Req() req: any,
    @Param('id') id: number,
    @UploadedFile() file: Express.Multer.File,
  ) {
    const userId = req.user?.id || req.user?.userId || req.user?.sub;
    return this.seekerResumesService.replaceResume(userId, id, file);
  }
}
