import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiResponse, ApiQuery } from '@nestjs/swagger';
import { WalletApplicationService } from '@/application/services';
import { GetMyLedgerQuery } from '@/application/queries';
import { CurrentUser, CurrentUserPayload } from '@/shared/decorators';
import { JwtAuthGuard } from '@/shared/guards/jwt-auth.guard';
import { GetMyLedgerQueryDTO } from '@/api/dto/request';
import { PaginatedLedgerResponseDTO, LedgerStatisticsResponseDTO, LedgerTrendResponseDTO } from '@/api/dto/response';

@ApiTags('Ledger')
@Controller('wallet/ledger')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class LedgerController {
  constructor(private readonly walletService: WalletApplicationService) {}

  @Get('my-ledger')
  @ApiOperation({ summary: '查询我的流水', description: '获取当前用户的账本流水记录' })
  @ApiResponse({ status: 200, type: PaginatedLedgerResponseDTO })
  async getMyLedger(
    @CurrentUser() user: CurrentUserPayload,
    @Query() queryDto: GetMyLedgerQueryDTO,
  ): Promise<PaginatedLedgerResponseDTO> {
    const query = new GetMyLedgerQuery(
      user.accountSequence,  // 使用 accountSequence 替代 userId
      queryDto.page,
      queryDto.pageSize,
      queryDto.entryType,
      queryDto.assetType,
      queryDto.startDate ? new Date(queryDto.startDate) : undefined,
      queryDto.endDate ? new Date(queryDto.endDate) : undefined,
    );
    return this.walletService.getMyLedger(query);
  }

  @Get('statistics')
  @ApiOperation({ summary: '获取流水统计', description: '按类型汇总用户的收支统计' })
  @ApiResponse({ status: 200, type: LedgerStatisticsResponseDTO })
  async getStatistics(
    @CurrentUser() user: CurrentUserPayload,
  ): Promise<LedgerStatisticsResponseDTO> {
    return this.walletService.getLedgerStatistics(user.accountSequence);
  }

  @Get('trend')
  @ApiOperation({ summary: '获取流水趋势', description: '按日期统计用户的收支趋势' })
  @ApiQuery({ name: 'days', required: false, description: '统计天数（默认30天）' })
  @ApiResponse({ status: 200, type: LedgerTrendResponseDTO })
  async getTrend(
    @CurrentUser() user: CurrentUserPayload,
    @Query('days') days?: string,
  ): Promise<LedgerTrendResponseDTO> {
    const numDays = days ? parseInt(days, 10) : 30;
    return this.walletService.getLedgerTrend(user.accountSequence, numDays);
  }
}
