import { Controller, Get, Post, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { LeaderboardApplicationService } from '../../application/services/leaderboard-application.service';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';
import { AdminGuard } from '../guards/admin.guard';
import { CurrentUser, CurrentUserPayload } from '../decorators/current-user.decorator';
import {
  QueryLeaderboardDto,
  LeaderboardRankingResponseDto,
  MyRankingResponseDto,
} from '../dto/leaderboard.dto';
import { LeaderboardType } from '../../domain/value-objects/leaderboard-type.enum';

@ApiTags('龙虎榜')
@Controller('leaderboard')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class LeaderboardController {
  constructor(
    private readonly leaderboardService: LeaderboardApplicationService,
  ) {}

  @Get()
  @ApiOperation({ summary: '获取龙虎榜列表' })
  @ApiQuery({ name: 'type', enum: LeaderboardType, description: '榜单类型' })
  @ApiQuery({ name: 'limit', required: false, description: '返回数量限制' })
  @ApiResponse({
    status: 200,
    description: '榜单列表',
    type: [LeaderboardRankingResponseDto],
  })
  async getLeaderboard(@Query() query: QueryLeaderboardDto) {
    const rankings = await this.leaderboardService.getLeaderboard(
      query.type,
      query.limit,
    );

    return {
      code: 0,
      message: 'success',
      data: rankings,
    };
  }

  @Get('my-ranking')
  @ApiOperation({ summary: '获取我的排名' })
  @ApiQuery({ name: 'type', enum: LeaderboardType, required: false, description: '榜单类型（不传返回所有）' })
  @ApiResponse({
    status: 200,
    description: '我的排名',
    type: MyRankingResponseDto,
  })
  async getMyRanking(
    @CurrentUser() user: CurrentUserPayload,
    @Query('type') type?: LeaderboardType,
  ) {
    const userId = BigInt(user.userId);

    if (type) {
      const ranking = await this.leaderboardService.getUserRanking(type, userId);
      return {
        code: 0,
        message: 'success',
        data: ranking,
      };
    }

    const rankings = await this.leaderboardService.getMyRankings(userId);
    return {
      code: 0,
      message: 'success',
      data: rankings,
    };
  }

  @Post('refresh')
  @UseGuards(AdminGuard)
  @ApiOperation({ summary: '手动刷新榜单（管理员）' })
  @ApiQuery({ name: 'type', enum: LeaderboardType, required: false, description: '榜单类型（不传刷新所有）' })
  @ApiResponse({ status: 200, description: '刷新成功' })
  async refreshLeaderboard(@Query('type') type?: LeaderboardType) {
    if (type) {
      await this.leaderboardService.refreshLeaderboard(type);
    } else {
      for (const t of Object.values(LeaderboardType)) {
        await this.leaderboardService.refreshLeaderboard(t as LeaderboardType);
      }
    }

    return {
      code: 0,
      message: '榜单刷新成功',
    };
  }
}
