import { Controller, Get, Post, Query, UseGuards, Request, DefaultValuePipe, ParseIntPipe } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../shared/guards/jwt-auth.guard';
import { RewardApplicationService } from '../../application/services/reward-application.service';
import { RewardSummaryDto } from '../dto/response/reward-summary.dto';
import { RewardEntryListDto } from '../dto/response/reward-entry.dto';
import { RewardStatus } from '../../domain/value-objects/reward-status.enum';
import { RightType } from '../../domain/value-objects/right-type.enum';

@ApiTags('Rewards')
@Controller('rewards')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class RewardController {
  constructor(private readonly rewardService: RewardApplicationService) {}

  @Get('summary')
  @ApiOperation({ summary: '获取我的收益汇总' })
  @ApiResponse({ status: 200, description: '成功', type: RewardSummaryDto })
  async getSummary(@Request() req): Promise<RewardSummaryDto> {
    const accountSequence = req.user.accountSequence;
    const summary = await this.rewardService.getRewardSummary(accountSequence);

    return {
      ...summary,
      pendingRemainingTimeMs: summary.pendingExpireAt
        ? Math.max(0, summary.pendingExpireAt.getTime() - Date.now())
        : 0,
    };
  }

  @Get('details')
  @ApiOperation({ summary: '获取我的奖励明细' })
  @ApiQuery({ name: 'status', required: false, enum: RewardStatus })
  @ApiQuery({ name: 'rightType', required: false, enum: RightType })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'pageSize', required: false, type: Number })
  @ApiResponse({ status: 200, description: '成功', type: RewardEntryListDto })
  async getDetails(
    @Request() req,
    @Query('status') status?: RewardStatus,
    @Query('rightType') rightType?: RightType,
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number = 1,
    @Query('pageSize', new DefaultValuePipe(20), ParseIntPipe) pageSize: number = 20,
  ) {
    const accountSequence = req.user.accountSequence;
    const filters: any = {};
    if (status) filters.status = status;
    if (rightType) filters.rightType = rightType;

    return this.rewardService.getRewardDetails(accountSequence, filters, { page, pageSize });
  }

  @Get('pending')
  @ApiOperation({ summary: '获取待领取奖励（含倒计时）' })
  @ApiResponse({ status: 200, description: '成功' })
  async getPending(@Request() req) {
    const accountSequence = req.user.accountSequence;
    return this.rewardService.getPendingRewards(accountSequence);
  }

  @Get('settleable')
  @ApiOperation({ summary: '获取可结算奖励列表' })
  @ApiResponse({ status: 200, description: '成功' })
  async getSettleable(@Request() req) {
    const accountSequence = req.user.accountSequence;
    return this.rewardService.getSettleableRewards(accountSequence);
  }

  @Post('settle-to-balance')
  @ApiOperation({
    summary: '结算到余额',
    description: '将可结算收益直接转入钱包USDT余额（无币种兑换）',
  })
  @ApiResponse({
    status: 200,
    description: '结算结果',
    schema: {
      type: 'object',
      properties: {
        success: { type: 'boolean', description: '是否成功' },
        settlementId: { type: 'string', description: '结算ID' },
        settledUsdtAmount: { type: 'number', description: '结算的USDT总额' },
        settledHashpowerAmount: { type: 'number', description: '结算的算力总额' },
        rewardCount: { type: 'number', description: '涉及的奖励数量' },
        breakdown: {
          type: 'object',
          description: '按权益类型分解',
          additionalProperties: { type: 'number' },
        },
        balanceAfter: { type: 'number', description: '结算后USDT余额' },
        error: { type: 'string', description: '错误信息（如果失败）' },
      },
    },
  })
  async settleToBalance(@Request() req) {
    const accountSequence = req.user.accountSequence;
    return this.rewardService.settleRewardsToBalance(accountSequence);
  }
}
