import { PaymentGateway, PaymentLinkResult, PaymentVerificationResult, SeamlessPaymentResult } from '../interfaces/payment-gateway.interface';
import { PrismaService } from '../../../prisma/prisma.service';

export class MockGateway implements PaymentGateway {
  private readonly baseUrl: string;

  constructor(private readonly prisma?: PrismaService) {
    this.baseUrl = process.env.FRONTEND_URL || 'http://localhost:3001';
  }

  async createPaymentLink(
    orderId: string,
    amount: number,
    currency: string,
    customerEmail: string,
    _callbackUrl: string,
  ): Promise<PaymentLinkResult> {
    const randSuffix = Math.floor(100000 + Math.random() * 900000);
    const paymentReference = `PAY-MOCK-${randSuffix}`;

    // The payment link points to our backend checkout route
    const paymentLink = `${this.baseUrl}/payments/checkout?reference=${paymentReference}&amount=${amount}&currency=${currency}&orderId=${orderId}&email=${encodeURIComponent(customerEmail)}`;

    return {
      paymentLink,
      paymentReference,
      gatewayReference: `GTW-MOCK-${randSuffix}`,
    };
  }

  async makeSeamlessPayment(
    orderId: string,
    amount: number,
    currency: string,
    ecocashNumber: string,
    _customerEmail: string,
    _reason: string,
    _callbackUrl: string,
  ): Promise<SeamlessPaymentResult> {
    // Mock: simulate a seamless EcoCash push initiation — auto-success for sandbox testing
    const randSuffix = Math.floor(100000 + Math.random() * 900000);
    const paymentReference = `PAY-MOCK-SEAMLESS-${randSuffix}`;

    console.log(`[MockGateway] Seamless EcoCash push initiated: ecocash=${ecocashNumber}, ref=${paymentReference}, amount=${currency} ${amount}, orderId=${orderId}`);

    return {
      paymentReference,
      pollUrl: '',
      gatewayReference: `GTW-MOCK-SEAMLESS-${randSuffix}`,
    };
  }

  async verifyPayment(paymentReference: string): Promise<PaymentVerificationResult> {
    if (this.prisma) {
      const payment = await this.prisma.payment.findUnique({
        where: { paymentReference },
      });
      if (payment) {
        return {
          status: payment.status as 'PENDING' | 'SUCCESS' | 'FAILED',
          gatewayReference: payment.gatewayReference || `GTW-VERIFY-${paymentReference}`,
          amount: payment.amount,
          rawResponse: JSON.stringify(payment),
        };
      }
    }

    return {
      status: 'SUCCESS',
      gatewayReference: `GTW-VERIFY-${paymentReference}`,
      amount: 10.0,
      rawResponse: JSON.stringify({ verified: true, mock: true }),
    };
  }
}
