import { NextRequest, NextResponse } from 'next/server';
import { getOrderById, updateOrderStatus } from '@/lib/db';

const MF_TOKEN = process.env.MF_API_KEY || 'YOUR_TEST_TOKEN_HERE';

const isLiveToken = MF_TOKEN.startsWith('SK_') && !MF_TOKEN.toLowerCase().includes('test');
const MF_BASE_URL = isLiveToken || process.env.MF_ENV === 'live'
  ? 'https://api.myfatoorah.com'
  : 'https://apitest.myfatoorah.com';

const PAYMENT_METHOD_MAP: Record<string, number> = {
  knet: 2,
  visa: 1,
  apple: 11,
};

export async function POST(req: NextRequest) {
  try {
    const { orderId, paymentMethod } = await req.json();
    const order = getOrderById(orderId);
    if (!order) return NextResponse.json({ success: false, message: 'Order not found' }, { status: 404 });

    const methodId = PAYMENT_METHOD_MAP[paymentMethod] || 2;
    const callbackBase = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';

    const payload = {
      PaymentMethodId: methodId,
      CustomerName: order.customerName,
      DisplayCurrencyIso: 'KWD',
      MobileCountryCode: '+965',
      CustomerMobile: order.phone.replace('+965', '').replace(/\s/g, ''),
      CustomerEmail: order.email || 'customer@fasttimephone.kw',
      InvoiceTotalAmount: order.total.toFixed(3),
      CallBackUrl: `${callbackBase}/api/payment/callback?orderId=${orderId}`,
      ErrorUrl: `${callbackBase}/checkout/failed?orderId=${orderId}`,
      Language: 'en',
      CustomerReference: orderId,
      InvoiceItems: order.items.map(item => ({
        ItemName: item.name,
        Quantity: item.quantity,
        UnitPrice: item.price.toFixed(3),
      })),
    };

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

    const data = await response.json();

    if (!data.IsSuccess) {
      return NextResponse.json({ success: false, message: data.Message || 'Payment initiation failed' }, { status: 400 });
    }

    return NextResponse.json({
      success: true,
      paymentUrl: data.Data?.PaymentURL,
      invoiceId: data.Data?.InvoiceId,
    });
  } catch (e: any) {
    return NextResponse.json({ success: false, message: e.message }, { status: 500 });
  }
}
