import {
  Controller,
  Get,
  Query,
  Req,
  UseGuards,
  ParseIntPipe,
  DefaultValuePipe,
  BadRequestException,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { ReferralService } from '../../../application/services/referral.service';

@ApiTags('Referral')
@Controller('referral')
export class ReferralController {
  constructor(private readonly referralService: ReferralService) {}

  /** 获取我的推荐信息 (推荐码 + 推荐人 + 直推人数) */
  @Get('my')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取我的推荐信息' })
  async getMyInfo(@Req() req: any) {
    const userId: string = req.user.sub;
    const info = await this.referralService.getMyInfo(userId);
    return { code: 0, data: info };
  }

  /** 验证推荐码是否有效 (公开接口，注册页面调用) */
  @Get('validate')
  @ApiOperation({ summary: '验证推荐码' })
  @ApiQuery({ name: 'code', description: '推荐码', example: 'GNXAB123' })
  async validateCode(@Query('code') code: string) {
    if (!code) throw new BadRequestException('缺少推荐码参数');
    const result = await this.referralService.validateCode(code);
    return { code: 0, data: result };
  }

  /** 获取我的直推列表 */
  @Get('direct')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取直推下级列表' })
  async getDirectReferrals(
    @Req() req: any,
    @Query('offset', new DefaultValuePipe(0), ParseIntPipe) offset: number,
    @Query('limit', new DefaultValuePipe(20), ParseIntPipe) limit: number,
  ) {
    const userId: string = req.user.sub;
    const result = await this.referralService.getDirectReferrals(userId, offset, Math.min(limit, 100));
    return { code: 0, data: result };
  }
}
