import {
  Controller,
  Get,
  Post,
  Body,
  Query,
  UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard } from '@/common';
import { CurrentUser } from '@/common/decorators/current-user.decorator';
import { WithdrawalService } from '@/modules/shared/finance/withdrawal.service';
import { TransactionService } from '@/modules/shared/finance/transaction.service';
import { AccountService } from '@/modules/shared/finance/account.service';
import {
  CreateUserWithdrawalDto,
  QueryUserWithdrawalDto,
  QueryTransactionDto,
} from '@/modules/shared/finance/dto/finance.dto';

@ApiTags('财务管理(用户)')
@Controller('app/finance')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class FinanceUserController {
  constructor(
    private readonly withdrawalService: WithdrawalService,
    private readonly transactionService: TransactionService,
    private readonly accountService: AccountService,
  ) {}

  @Get('wallet')
  @ApiOperation({ summary: '获取钱包信息' })
  async getWallet(@CurrentUser('sub') userId: number) {
    const account = await this.accountService.getUserAccount(userId);

    return {
      balance: account.balance,
      frozenBalance: account.frozen_balance,
      availableBalance: Number(account.balance) - Number(account.frozen_balance),
    };
  }

  @Post('withdraw')
  @ApiOperation({ summary: '申请提现' })
  async createWithdrawal(
    @CurrentUser('sub') userId: number,
    @Body() dto: CreateUserWithdrawalDto,
  ) {
    return this.withdrawalService.createUserWithdrawal(userId, dto);
  }

  @Get('withdrawals')
  @ApiOperation({ summary: '提现记录列表' })
  async getWithdrawals(
    @CurrentUser('sub') userId: number,
    @Query() dto: QueryUserWithdrawalDto,
  ) {
    return this.withdrawalService.getUserWithdrawals({
      userId,
      status: dto.status,
      page: dto.page,
      pageSize: dto.pageSize,
    });
  }

  @Get('transactions')
  @ApiOperation({ summary: '交易流水列表' })
  async getTransactions(
    @CurrentUser('sub') userId: number,
    @Query() dto: QueryTransactionDto,
  ) {
    const account = await this.accountService.getUserAccount(userId);

    return this.transactionService.getUserTransactions({
      accountId: account.id,
      direction: dto.direction,
      transactionType: dto.transactionType,
      startDate: dto.startDate,
      endDate: dto.endDate,
      page: dto.page,
      pageSize: dto.pageSize,
    });
  }
}
