export const MYFATOORAH_API_URL = process.env.MYFATOORAH_API_URL || 'https://apitest.myfatoorah.com';
export const MYFATOORAH_API_KEY = process.env.MYFATOORAH_API_KEY || '';

export async function executePayment({
  invoiceValue,
  customerName,
  customerEmail,
  customerMobile,
  orderId,
  paymentMethodId = 2, // Default to Visa/Mastercard, 1 is KNET in Kuwait
}: {
  invoiceValue: number;
  customerName: string;
  customerEmail?: string;
  customerMobile?: string;
  orderId: string;
  paymentMethodId?: number;
}) {
  const payload = {
    PaymentMethodId: paymentMethodId,
    CustomerName: customerName || 'Guest Customer',
    DisplayCurrencyIso: 'KWD',
    CustomerMobile: customerMobile || '',
    CustomerEmail: customerEmail || '',
    InvoiceValue: invoiceValue,
    CallBackUrl: `${process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'}/api/payment/callback?orderId=${orderId}`,
    ErrorUrl: `${process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'}/api/payment/error?orderId=${orderId}`,
    Language: 'en',
    CustomerReference: orderId,
  };

  const response = await fetch(`${MYFATOORAH_API_URL}/v2/ExecutePayment`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${MYFATOORAH_API_KEY}`,
    },
    body: JSON.stringify(payload),
  });

  const data = await response.json();

  if (!response.ok || !data.IsSuccess) {
    throw new Error(data.Message || 'Payment gateway error');
  }

  return {
    paymentUrl: data.Data.PaymentURL,
    invoiceId: data.Data.InvoiceId,
  };
}

export async function getPaymentStatus(paymentId: string) {
  const payload = {
    Key: paymentId,
    KeyType: 'PaymentId'
  };

  const response = await fetch(`${MYFATOORAH_API_URL}/v2/GetPaymentStatus`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${MYFATOORAH_API_KEY}`,
    },
    body: JSON.stringify(payload),
  });

  const data = await response.json();
  return data;
}
