import { Controller, Post, Body, Param, HttpCode, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
import { OrdersService } from '../commerce/services/orders.service';
import { PrismaService } from '../../prisma/prisma.service';
import { SubscriptionEngineService } from '../subscription/subscription-engine.service';

@Controller('webhooks/payments')
export class PaymentsWebhookController {
  private readonly logger = new Logger(PaymentsWebhookController.name);

  constructor(
    private readonly ordersService: OrdersService,
    private readonly prisma: PrismaService,
    private readonly subscriptionEngine: SubscriptionEngineService,
  ) {}

  // 1. Mock Sandbox Payment Webhook
  @Post('mock')
  @HttpCode(HttpStatus.OK)
  async handleMockWebhook(
    @Body() body: { reference: string; status: 'SUCCESS' | 'FAILED'; gatewayReference?: string },
  ) {
    const { reference, status, gatewayReference } = body;
    this.logger.log(`Mock payment webhook received: ref=${reference}, status=${status}`);
    
    const order = await this.ordersService.confirmPayment(reference, status, gatewayReference || 'MOCK-REF-123');
    
    return { success: true, orderId: order.id, status: order.status };
  }

  // 2. Paynow Webhook Receiver
  @Post('paynow')
  @HttpCode(HttpStatus.OK)
  async handlePaynowWebhook(@Body() body: any) {
    this.logger.log('Paynow webhook received body:', JSON.stringify(body));

    const reference = body.reference;
    if (!reference) {
      return { error: 'Missing reference' };
    }

    await this.ordersService.verifyAndConfirmPayment(reference);
    return 'OK'; // Paynow expects a response
  }

  @Post('pesepay')
  @HttpCode(HttpStatus.OK)
  async handlePesepayWebhook(@Body() body: any) {
    this.logger.log('PesePay webhook received body:', JSON.stringify(body));
    
    const reference = body.referenceNumber || body.reference;
    if (!reference) {
      return { error: 'Missing referenceNumber' };
    }

    if (reference.startsWith('SUB-')) {
      await this.subscriptionEngine.confirmSubscription(reference, body.transactionId || reference);
      return { success: true };
    }

    await this.ordersService.verifyAndConfirmPayment(reference);
    return { success: true };
  }
}
