import {
  Body,
  Controller,
  Get,
  Param,
  Post,
  Req,
  Res,
  UseGuards,
  UsePipes,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe';
import { ApiKeyGuard } from './api-key.guard';
import {
  publicApplyDto,
  publicApplySchema,
  publicApiApplyDto,
  publicApiApplySchema,
  submitRecruitmentTaskDto,
  submitRecruitmentTaskSchema,
} from './recruitment.dto';
import { RecruitmentService } from './recruitment.service';

@Controller('public')
export class PublicRecruitmentController {
  constructor(private readonly service: RecruitmentService) {}

  @Get('careers/:orgSlug/jobs')
  async getPublicJobs(
    @Param('orgSlug') orgSlug: string,
    @Res() res: Response,
  ) {
    const result = await this.service.getPublicJobs(orgSlug);
    return res.status(result.status).json(result);
  }

  @Get('careers/:orgSlug/jobs/:jobSlug')
  async getPublicJob(
    @Param('orgSlug') orgSlug: string,
    @Param('jobSlug') jobSlug: string,
    @Res() res: Response,
  ) {
    const result = await this.service.getPublicJob(orgSlug, jobSlug);
    return res.status(result.status).json(result);
  }

  @UsePipes(new ZodValidationPipe(publicApplySchema))
  @Post('careers/:orgSlug/jobs/:jobSlug/apply')
  async publicApply(
    @Param('orgSlug') orgSlug: string,
    @Param('jobSlug') jobSlug: string,
    @Body() data: publicApplyDto,
    @Res() res: Response,
  ) {
    const result = await this.service.publicApply(orgSlug, jobSlug, data);
    return res.status(result.status).json(result);
  }

  @UseGuards(ApiKeyGuard)
  @Get('v1/jobs')
  async publicApiJobs(@Req() req: Request, @Res() res: Response) {
    const result = await this.service.publicApiListJobs(
      (req as any).tenantOwnerId,
    );
    return res.status(result.status).json(result);
  }

  @UseGuards(ApiKeyGuard)
  @UsePipes(new ZodValidationPipe(publicApiApplySchema))
  @Post('v1/applications')
  async publicApiApply(
    @Req() req: Request,
    @Body() body: publicApiApplyDto,
    @Res() res: Response,
  ) {
    const result = await this.service.publicApiCreateApplication(
      (req as any).tenantOwnerId,
      body,
    );
    return res.status(result.status).json(result);
  }

  @Get('recruitment-tasks/:token')
  async getTaskByToken(@Param('token') token: string, @Res() res: Response) {
    const result = await this.service.getTaskByToken(token);
    return res.status(result.status).json(result);
  }

  @UsePipes(new ZodValidationPipe(submitRecruitmentTaskSchema))
  @Post('recruitment-tasks/:token/submit')
  async submitTaskByToken(
    @Param('token') token: string,
    @Body() data: submitRecruitmentTaskDto,
    @Res() res: Response,
  ) {
    const result = await this.service.submitTaskByToken(token, data);
    return res.status(result.status).json(result);
  }
}
