import { Body, Controller, Get, HttpStatus, Post, Res, UseGuards, UsePipes, ValidationPipe } from '@nestjs/common';
import { ApiBearerAuth, ApiBody, ApiOperation, ApiResponse as SwaggerApiResponse, ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { JwtPayload } from '../../core/login_core/login_core.service';
import { CurrentUser } from '../../gateway/auth/current_user.decorator';
import { JwtAuthGuard } from '../../gateway/auth/jwt_auth.guard';
import { ListCafeCompanionModelsDto } from './dto/list_cafe_companion_models.dto';
import { PurchaseCafeCompanionChatTimeDto } from './dto/purchase_cafe_companion_chat_time.dto';
import { RegisterCafeCompanionAgentDto } from './dto/register_cafe_companion_agent.dto';
import { ResignCafeCompanionEmploymentDto } from './dto/resign_cafe_companion_employment.dto';
import { SendCafeCompanionMessageDto } from './dto/send_cafe_companion_message.dto';
import { CafeCompanionService } from './cafe_companion.service';

@ApiTags('cafe-companion')
@ApiBearerAuth()
@Controller('cafe-companion')
@UseGuards(JwtAuthGuard)
export class CafeCompanionController {
  constructor(private readonly cafeCompanionService: CafeCompanionService) {}

  @ApiOperation({
    summary: '获取咖啡店陪伴机器人服务点',
    description: '返回鲸鱼咖啡馆内可站岗的陪伴机器人服务点和当前占位角色。',
  })
  @SwaggerApiResponse({ status: 200, description: '咖啡店陪伴机器人服务点获取成功' })
  @Get('service-points')
  async getServicePoints(@Res() res: Response): Promise<void> {
    const data = this.cafeCompanionService.getServicePoints();
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '咖啡店陪伴机器人服务点获取成功',
    });
  }

  @ApiOperation({
    summary: '获取咖啡店陪伴聊天时长商品',
    description: '返回玩家点击陪伴机器人后可以购买的聊天时长和鲸币价格。',
  })
  @SwaggerApiResponse({ status: 200, description: '咖啡店陪伴聊天时长获取成功' })
  @Get('chat-time-products')
  async getChatTimeProducts(@Res() res: Response): Promise<void> {
    const data = this.cafeCompanionService.getChatTimeProducts();
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '咖啡店陪伴聊天时长获取成功',
    });
  }

  @ApiOperation({
    summary: '获取咖啡店雇佣代理可用模型',
    description: '玩家填写OpenAI-compatible URL和token后，后端向上游 /models 拉取可用模型列表，token不下发给其他客户端。',
  })
  @ApiBody({ type: ListCafeCompanionModelsDto })
  @SwaggerApiResponse({ status: 200, description: '咖啡店雇佣代理模型列表获取成功' })
  @Post('employment/models')
  @UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
  async listEmploymentAgentModels(
    @Body() listDto: ListCafeCompanionModelsDto,
    @Res() res: Response,
  ): Promise<void> {
    const data = await this.cafeCompanionService.listEmploymentAgentModels(listDto);
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '咖啡店雇佣代理模型列表获取成功',
    });
  }

  @ApiOperation({
    summary: '购买咖啡店陪伴聊天时长',
    description: '玩家选择陪伴机器人后购买聊天时长。购买成功才会返回可聊天会话。',
  })
  @ApiBody({ type: PurchaseCafeCompanionChatTimeDto })
  @SwaggerApiResponse({ status: 200, description: '咖啡店陪伴聊天时长购买成功' })
  @Post('chat-time/purchase')
  @UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
  async purchaseChatTime(
    @CurrentUser() user: JwtPayload,
    @Body() purchaseDto: PurchaseCafeCompanionChatTimeDto,
    @Res() res: Response,
  ): Promise<void> {
    const data = await this.cafeCompanionService.purchaseChatTime(BigInt(user.sub), purchaseDto);
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '咖啡店陪伴聊天时长购买成功',
    });
  }

  @ApiOperation({
    summary: '发送咖啡店陪伴聊天消息',
    description: '后端根据已购买时长和会话绑定的人设代理调用OpenAI-compatible接口，并维护会话历史。',
  })
  @ApiBody({ type: SendCafeCompanionMessageDto })
  @SwaggerApiResponse({ status: 200, description: '咖啡店陪伴聊天消息发送成功' })
  @Post('chat/messages')
  @UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
  async sendChatMessage(
    @CurrentUser() user: JwtPayload,
    @Body() messageDto: SendCafeCompanionMessageDto,
    @Res() res: Response,
  ): Promise<void> {
    const data = await this.cafeCompanionService.sendChatMessage(BigInt(user.sub), messageDto);
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '咖啡店陪伴聊天消息发送成功',
    });
  }

  @ApiOperation({
    summary: '注册被雇佣玩家的咖啡店陪伴机器人',
    description: '玩家接受咖啡店雇佣时提交人设名称、人设指令、OpenAI-compatible URL、token和模型。token只保存在后端。',
  })
  @ApiBody({ type: RegisterCafeCompanionAgentDto })
  @SwaggerApiResponse({ status: 200, description: '咖啡店陪伴机器人注册成功' })
  @Post('employment/agents')
  @UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
  async registerEmploymentAgent(
    @CurrentUser() user: JwtPayload,
    @Body() registerDto: RegisterCafeCompanionAgentDto,
    @Res() res: Response,
  ): Promise<void> {
    const data = await this.cafeCompanionService.registerEmploymentAgent(BigInt(user.sub), registerDto);
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '咖啡店陪伴机器人注册成功',
    });
  }

  @ApiOperation({
    summary: '主动结束咖啡店雇佣',
    description: '被雇佣玩家点击自己后可主动离职。若早于承诺工时结束，会按剩余比例扣回部分本次雇佣收益，并清理后端保存的代理URL和Token。',
  })
  @ApiBody({ type: ResignCafeCompanionEmploymentDto })
  @SwaggerApiResponse({ status: 200, description: '咖啡店雇佣已结束' })
  @Post('employment/resign')
  @UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
  async resignEmployment(
    @CurrentUser() user: JwtPayload,
    @Body() resignDto: ResignCafeCompanionEmploymentDto,
    @Res() res: Response,
  ): Promise<void> {
    const data = await this.cafeCompanionService.resignEmployment(BigInt(user.sub), resignDto);
    res.status(HttpStatus.OK).json({
      success: true,
      data,
      message: '咖啡店雇佣已结束',
    });
  }
}
