import { Body, Controller, Get, Post, Query, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { AuthenticatedUser } from '../auth/auth.types';
import { AuthGuard } from '../common/auth.guard';
import { RequirePermission } from '../common/permission.decorator';
import { PermissionGuard } from '../common/permission.guard';
import { CreateMidtransTopupDto } from './dto/create-midtrans-topup.dto';
import { CreateManualTopupDto } from './dto/create-manual-topup.dto';
import { WalletService } from './wallet.service';

@UseGuards(AuthGuard, PermissionGuard)
@Controller('wallet')
export class WalletController {
  constructor(private readonly walletService: WalletService) {}

  @Get()
  @RequirePermission('settings', 'view')
  getSummary(@Query('limit') limit?: string) {
    return this.walletService.getSummary(limit ? Number(limit) : 20);
  }

  @Get('estimate-broadcast')
  @RequirePermission('campaigns', 'view')
  estimateBroadcast(@Query('recipients') recipients?: string) {
    return this.walletService.estimateBroadcastCost(Number(recipients || '0'));
  }

  @Post('topups/manual')
  @RequirePermission('settings', 'manage')
  createManualTopup(
    @Req() request: Request & { user: AuthenticatedUser },
    @Body() dto: CreateManualTopupDto,
  ) {
    return this.walletService.createManualTopup(dto.amountMinor, dto.description, request.user, request.ip);
  }

  @Post('topups/midtrans')
  @RequirePermission('settings', 'manage')
  createMidtransTopup(
    @Req() request: Request & { user: AuthenticatedUser },
    @Body() dto: CreateMidtransTopupDto,
  ) {
    return this.walletService.createMidtransTopup(dto.amountMinor, dto.description, request.user);
  }
}

@Controller('wallet/midtrans')
export class WalletMidtransWebhookController {
  constructor(private readonly walletService: WalletService) {}

  @Post('notification')
  handleNotification(@Body() payload: Record<string, unknown>) {
    return this.walletService.handleMidtransNotification(payload);
  }
}
