import { Controller, Get, Post, Body, Query, UseGuards } from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiResponse,
  ApiQuery,
} from '@nestjs/swagger';
import { UserApplicationService } from '@/application/services/user-application.service';
import {
  JwtAuthGuard,
  Public,
  CurrentUser,
  CurrentUserData,
} from '@/shared/guards/jwt-auth.guard';
import {
  ValidateReferralCodeQuery,
  GetReferralStatsQuery,
  GenerateReferralLinkCommand,
} from '@/application/commands';
import {
  GenerateReferralLinkDto,
  MeResponseDto,
  ReferralValidationResponseDto,
  ReferralLinkResponseDto,
  ReferralStatsResponseDto,
} from '@/api/dto';

@ApiTags('Referrals')
@Controller()
@UseGuards(JwtAuthGuard)
export class ReferralsController {
  constructor(private readonly userService: UserApplicationService) {}

  /**
   * GET /api/me - 获取当前登录用户信息 + 推荐码
   */
  @Get('me')
  @ApiBearerAuth()
  @ApiOperation({
    summary: '获取当前登录用户信息',
    description: '返回用户基本信息、推荐码和推荐链接',
  })
  @ApiResponse({ status: 200, type: MeResponseDto })
  async getMe(@CurrentUser() user: CurrentUserData): Promise<MeResponseDto> {
    return this.userService.getMe(user.userId);
  }

  /**
   * GET /api/referrals/validate - 校验推荐码是否合法
   */
  @Public()
  @Get('referrals/validate')
  @ApiOperation({
    summary: '校验推荐码',
    description: '创建账号时校验推荐码是否合法',
  })
  @ApiQuery({ name: 'code', description: '推荐码', required: true })
  @ApiResponse({ status: 200, type: ReferralValidationResponseDto })
  async validateReferralCode(
    @Query('code') code: string,
  ): Promise<ReferralValidationResponseDto> {
    return this.userService.validateReferralCode(
      new ValidateReferralCodeQuery(code),
    );
  }

  /**
   * POST /api/referrals/links - 为当前登录用户生成短链/渠道链接
   */
  @Post('referrals/links')
  @ApiBearerAuth()
  @ApiOperation({
    summary: '生成推荐链接',
    description: '为当前登录用户生成短链/渠道链接',
  })
  @ApiResponse({ status: 201, type: ReferralLinkResponseDto })
  async generateReferralLink(
    @CurrentUser() user: CurrentUserData,
    @Body() dto: GenerateReferralLinkDto,
  ): Promise<ReferralLinkResponseDto> {
    return this.userService.generateReferralLink(
      new GenerateReferralLinkCommand(user.userId, dto.channel, dto.campaignId),
    );
  }

  /**
   * GET /api/referrals/stats - 查询登录用户的邀请记录
   */
  @Get('referrals/stats')
  @ApiBearerAuth()
  @ApiOperation({
    summary: '查询邀请统计',
    description: '查询登录用户的邀请记录和统计数据',
  })
  @ApiResponse({ status: 200, type: ReferralStatsResponseDto })
  async getReferralStats(
    @CurrentUser() user: CurrentUserData,
  ): Promise<ReferralStatsResponseDto> {
    return this.userService.getReferralStats(
      new GetReferralStatsQuery(user.userId),
    );
  }
}
