import {
  Controller,
  Get,
  Post,
  Param,
  Body,
  Query,
  UseGuards,
  ParseUUIDPipe,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { CurrentUser, JwtPayload } from '../../../common/decorators/current-user.decorator';
import { RequireModule } from '../../../common/decorators/require-module.decorator';
import { ModuleGuard } from '../../../common/guards/module.guard';
import { Roles, UserRole } from '../../../common/decorators/roles.decorator';
import { RolesGuard } from '../../auth/guards/roles.guard';
import { PaymentService } from '../services/payment.service';
import { CreatePaymentDto, PaymentCallbackDto, RefundPaymentDto } from '../dto/payment.dto';

@ApiTags('Booking / Payments')
@ApiBearerAuth()
@Controller('booking/payments')
@UseGuards(JwtAuthGuard, ModuleGuard, RolesGuard)
@RequireModule('booking')
export class BookingPaymentsController {
  constructor(private readonly payments: PaymentService) {}

  @Get()
  @ApiOperation({ summary: 'List payments' })
  @ApiQuery({ name: 'cursor', required: false })
  @ApiQuery({ name: 'limit', required: false })
  @ApiQuery({ name: 'from', required: false, example: '2026-03-01' })
  @ApiQuery({ name: 'to', required: false, example: '2026-03-31' })
  async findAll(
    @CurrentUser() user: JwtPayload,
    @Query('cursor') cursor?: string,
    @Query('limit') limitStr?: string,
    @Query('from') from?: string,
    @Query('to') to?: string,
  ) {
    return this.payments.findAll(user.clubId, {
      cursor,
      limit: parseInt(limitStr || '50', 10) || 50,
      from,
      to,
    });
  }

  @Get('record/:recordId')
  @ApiOperation({ summary: 'List payments for a record' })
  async findByRecord(@Param('recordId', ParseUUIDPipe) recordId: string) {
    return this.payments.findByRecord(recordId);
  }

  @Post()
  @ApiOperation({ summary: 'Create payment' })
  @Roles(UserRole.RECEPTIONIST, UserRole.MANAGER, UserRole.CLUB_ADMIN, UserRole.SUPER_ADMIN)
  async create(@CurrentUser() user: JwtPayload, @Body() dto: CreatePaymentDto) {
    return this.payments.create(user.clubId, dto, user.sub);
  }

  @Post('callback')
  @ApiOperation({ summary: 'Payment provider callback (ЮKassa, Т-Банк, СБП)' })
  async callback(@Body() dto: PaymentCallbackDto) {
    return this.payments.processCallback(dto);
  }

  @Post(':id/refund')
  @ApiOperation({ summary: 'Refund payment' })
  @Roles(UserRole.MANAGER, UserRole.CLUB_ADMIN, UserRole.SUPER_ADMIN)
  async refund(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: RefundPaymentDto,
  ) {
    return this.payments.refund(id, dto, user.sub);
  }
}
