import { Controller, Get, Post, Body, Query, UseGuards, Req } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { IssuerFinanceService } from '../../../application/services/issuer-finance.service';
import {
  WithdrawDto,
  ListTransactionsQueryDto,
  ReconciliationQueryDto,
} from '../dto/issuer-finance.dto';

@ApiTags('Issuer Finance')
@Controller('issuers/me/finance')
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
export class IssuerFinanceController {
  constructor(private readonly issuerFinanceService: IssuerFinanceService) {}

  @Get('balance')
  @ApiOperation({ summary: 'Get issuer financial balance' })
  async getBalance(@Req() req: any) {
    const balance = await this.issuerFinanceService.getBalance(req.user.issuerId);
    return { code: 0, data: balance };
  }

  @Get('stats')
  @ApiOperation({ summary: 'Get issuer finance summary' })
  async getFinanceStats(@Req() req: any) {
    const stats = await this.issuerFinanceService.getFinanceStats(req.user.issuerId);
    return { code: 0, data: stats };
  }

  @Get('transactions')
  @ApiOperation({ summary: 'Get issuer transaction history' })
  async getTransactions(@Req() req: any, @Query() query: ListTransactionsQueryDto) {
    const result = await this.issuerFinanceService.getTransactions(
      req.user.issuerId,
      query.page || 1,
      query.limit || 20,
      query.type,
    );
    return { code: 0, data: result };
  }

  @Post('withdraw')
  @ApiOperation({ summary: 'Request a withdrawal' })
  async requestWithdrawal(@Req() req: any, @Body() dto: WithdrawDto) {
    const result = await this.issuerFinanceService.requestWithdrawal(
      req.user.issuerId,
      dto.amount,
    );
    return { code: 0, data: result };
  }

  @Get('reconciliation')
  @ApiOperation({ summary: 'Get reconciliation data' })
  async getReconciliation(@Req() req: any, @Query() query: ReconciliationQueryDto) {
    const result = await this.issuerFinanceService.getReconciliation(
      req.user.issuerId,
      query.startDate,
      query.endDate,
    );
    return { code: 0, data: result };
  }
}
