import { IPaymentGateway } from '../interfaces/payment-gateway.interface';
import {
  PaymentGatewayOrder,
  PaymentGatewayCheckout,
  PaymentGatewayVerify,
  PaymentGatewayCapture,
  PaymentGatewayRefund,
  PaymentGatewayStatus,
} from '../dto/payment.dto';
import { paymentConfig } from '../../../config/payment.config';
import { logger } from '../../../config/logger';

export class PayPalGateway implements IPaymentGateway {
  private clientId: string;
  private clientSecret: string;

  constructor(config?: any) {
    this.clientId = config?.clientId || paymentConfig.paypal.clientId;
    this.clientSecret = config?.clientSecret || paymentConfig.paypal.clientSecret;
  }

  async createOrder(order: any): Promise<PaymentGatewayOrder> {
    const paypalOrderId = `pp_ord_${Date.now()}`;
    return {
      id: order.id,
      gatewayOrderId: paypalOrderId,
      amount: Number(order.grandTotal),
      currency: 'USD', // PayPal standard conversion
      status: 'CREATED',
    };
  }

  async createCheckout(checkout: any): Promise<PaymentGatewayCheckout> {
    return {
      checkoutUrl: `https://www.sandbox.paypal.com/checkoutnow?token=${checkout.gatewayOrderId}`,
      gatewayTransactionId: checkout.gatewayOrderId,
    };
  }

  async verifyPayment(payload: any): Promise<PaymentGatewayVerify> {
    const isSuccess = payload.status === 'COMPLETED' || payload.status === 'success';
    return {
      success: isSuccess,
      status: isSuccess ? 'SUCCESS' : 'FAILED',
      gatewayPaymentId: payload.payerId || `pp_pay_${Date.now()}`,
      gatewayTransactionId: payload.orderId || payload.paypalOrderId,
      message: 'PayPal payment status verified',
      rawResponse: payload,
    };
  }

  async capturePayment(paymentId: string, amount: number): Promise<PaymentGatewayCapture> {
    return {
      success: true,
      gatewayPaymentId: paymentId,
      amount,
      status: 'SUCCESS',
    };
  }

  async refundPayment(transactionId: string, amount: number, reason?: string): Promise<PaymentGatewayRefund> {
    const refundId = `pp_ref_${Date.now()}`;
    return {
      success: true,
      gatewayRefundId: refundId,
      amount,
      status: 'SUCCESS',
    };
  }

  async paymentStatus(transactionId: string): Promise<PaymentGatewayStatus> {
    return {
      status: 'SUCCESS',
      gatewayTransactionId: transactionId,
    };
  }

  async handleCallback(payload: any): Promise<any> {
    return this.verifyPayment(payload);
  }

  async handleWebhook(payload: any, signature?: string): Promise<any> {
    const event = payload.event_type;
    const resource = payload.resource;

    let status = 'PENDING';
    if (event === 'PAYMENT.CAPTURE.COMPLETED') status = 'SUCCESS';
    else if (event === 'PAYMENT.CAPTURE.DENIED') status = 'FAILED';
    else if (event === 'PAYMENT.CAPTURE.REFUNDED') status = 'REFUNDED';

    return {
      event,
      orderId: resource?.supplementary_data?.related_ids?.order_id || resource?.id,
      paymentId: resource?.id,
      status,
    };
  }

  async generateReceipt(paymentId: string): Promise<any> {
    return { receiptId: `pp_rcpt_${paymentId}` };
  }

  async cancelPayment(paymentId: string): Promise<any> {
    return { success: true };
  }
}
