import { Controller, Post, Get, Delete, Param, Body, Res, HttpException, HttpStatus } from '@nestjs/common'
import { Response } from 'express'
import { ResumeService } from './resume.service'
import { ResumePdfService } from './resume-pdf.service'
import { QuotaService } from '../user/quota.service'
import { CurrentUser } from '../../common/decorators/current-user.decorator'

@Controller('resume')
export class ResumeController {
  constructor(
    private resumeService: ResumeService,
    private resumePdfService: ResumePdfService,
    private quotaService: QuotaService,
  ) {}

  @Post('create')
  async create(
    @CurrentUser('userId') userId: string,
    @Body('title') title: string,
    @Body('content') content: string,
    @Body('targetPosition') targetPosition?: string,
  ) {
    return this.resumeService.create(userId, title, content, targetPosition)
  }

  @Get('list')
  async list(@CurrentUser('userId') userId: string) {
    return this.resumeService.list(userId)
  }

  @Post(':id/download')
  async download(@Param('id') id: string, @CurrentUser('userId') userId: string, @Res() res: Response) {
    const resume = await this.resumeService.getDetail(id, userId)
    const canDownload = await this.quotaService.checkAndDeductDownload(userId, resume.paidDownload)
    if (!canDownload && !resume.paidDownload) {
      throw new HttpException('请先付费下载', HttpStatus.PAYMENT_REQUIRED)
    }
    if (!resume.paidDownload) {
      await this.resumeService.markPaid(id, userId)
    }

    const pdf = await this.resumePdfService.generatePdf({
      title: resume.title,
      content: resume.content,
      targetPosition: resume.targetPosition,
    })

    res.setHeader('Content-Type', 'application/pdf')
    res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(resume.title)}.pdf"`)
    res.send(pdf)
  }

  @Get(':id')
  async getDetail(@Param('id') id: string, @CurrentUser('userId') userId: string) {
    return this.resumeService.getDetail(id, userId)
  }

  @Delete(':id')
  async delete(@Param('id') id: string, @CurrentUser('userId') userId: string) {
    return this.resumeService.delete(id, userId)
  }
}
