import { Controller, Post, Body, HttpException, HttpStatus, UseGuards } from '@nestjs/common'
import { AnalyzeService } from './analyze.service'
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
import { CurrentUser } from '../../common/decorators/current-user.decorator'
import { UserService } from '../user/user.service'

@Controller('analyze')
export class AnalyzeController {
  constructor(
    private analyzeService: AnalyzeService,
    private userService: UserService,
  ) {}

  @UseGuards(JwtAuthGuard)
  @Post('diagnosis')
  async diagnosis(@Body('content') content: string, @CurrentUser('userId') userId: string) {
    await this.checkAnalyzeLimit(userId)
    return this.analyzeService.diagnose(content)
  }

  @UseGuards(JwtAuthGuard)
  @Post('optimize')
  async optimize(@Body('content') content: string, @Body('direction') direction: string, @CurrentUser('userId') userId: string) {
    await this.checkAnalyzeLimit(userId)
    return this.analyzeService.optimize(content, direction)
  }

  private async checkAnalyzeLimit(userId: string) {
    const user = await this.userService.getModel().findById(userId).exec()
    if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
    if (user.plan === 'vip') return // VIP 不限次
    if (user.remaining <= 0) {
      throw new HttpException('免费版每日次数已用完，升级会员后不限次使用', HttpStatus.FORBIDDEN)
    }
    // 扣减一次
    user.remaining -= 1
    await user.save()
  }
}
