import { Controller, Get, Post, Put, Body, Param, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { SettlementService } from '../../../application/services/settlement.service';
import { RefundService } from '../../../application/services/refund.service';
import { BreakageService } from '../../../application/services/breakage.service';
import { ListSettlementsQueryDto } from '../dto/settlement.dto';
import { CreateRefundDto, ApproveRefundDto, ListRefundsQueryDto } from '../dto/refund.dto';

@ApiTags('Clearing')
@Controller('payments')
export class ClearingController {
  constructor(
    private readonly settlementService: SettlementService,
    private readonly refundService: RefundService,
    private readonly breakageService: BreakageService,
  ) {}

  @Get('settlements')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'List settlements' })
  async listSettlements(@Query() query: ListSettlementsQueryDto) {
    return {
      code: 0,
      data: await this.settlementService.list(
        +(query.page || '1'),
        +(query.limit || '20'),
        query.status,
      ),
    };
  }

  @Post('refunds')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Request a refund' })
  async createRefund(@Body() body: CreateRefundDto) {
    return { code: 0, data: await this.refundService.createRefund(body) };
  }

  @Put('refunds/:id/approve')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Approve a refund' })
  async approveRefund(@Param('id') id: string, @Body() body: ApproveRefundDto) {
    await this.refundService.approveRefund(id, body.processedBy);
    return { code: 0, data: null };
  }

  @Get('refunds')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'List refunds' })
  async listRefunds(@Query() query: ListRefundsQueryDto) {
    return {
      code: 0,
      data: await this.refundService.listRefunds(
        +(query.page || '1'),
        +(query.limit || '20'),
        query.status,
      ),
    };
  }
}
