import type { APIRoute } from 'astro';
import { supabaseAdmin } from '../../../../lib/supabase';
import { createPaySoClient, isPaymentSuccess } from '../../../../lib/payso';

export const POST: APIRoute = async ({ request }) => {
  try {
    const contentType = request.headers.get('content-type');
    let params: URLSearchParams;
    
    if (contentType?.includes('application/json')) {
      const body = await request.json();
      params = new URLSearchParams(body);
    } else if (contentType?.includes('application/x-www-form-urlencoded')) {
      const text = await request.text();
      params = new URLSearchParams(text);
    } else {
      const url = new URL(request.url);
      params = url.searchParams;
    }
    
    const refNo = params.get('refno') || params.get('Refno');
    const status = params.get('status') || params.get('Status');
    const amt = params.get('amt') || params.get('Amt');
    const apprvcode = params.get('apprvcode') || params.get('Apprvcode');
    
    if (!refNo) {
      console.error('PaySo webhook: Missing refno');
      return new Response('Missing refno', { status: 400 });
    }
    
    console.log(`PaySo webhook received: refno=${refNo}, status=${status}, amt=${amt}`);
    
    let paymentStatus: 'pending' | 'paid' | 'failed' = 'pending';
    let orderStatus: 'pending' | 'confirmed' | 'cancelled' = 'pending';
    
    if (isPaymentSuccess(status || '')) {
      paymentStatus = 'paid';
      orderStatus = 'confirmed';
    } else if (status === '2' || status === '3') {
      paymentStatus = 'failed';
      orderStatus = 'cancelled';
    }
    
    const { data: existingOrder } = await supabaseAdmin
      .from('orders')
      .select('id, order_number, payment_status')
      .eq('order_number', refNo)
      .single();
    
    if (!existingOrder) {
      console.error(`PaySo webhook: Order not found for refno=${refNo}`);
      return new Response('Order not found', { status: 404 });
    }
    
    if (existingOrder.payment_status === 'paid' && paymentStatus === 'paid') {
      return new Response('Already processed', { status: 200 });
    }
    
    const { data: order, error } = await supabaseAdmin
      .from('orders')
      .update({
        payment_status: paymentStatus,
        status: paymentStatus === 'paid' ? 'confirmed' : existingOrder.payment_status === 'paid' ? 'confirmed' : orderStatus,
        paid_at: paymentStatus === 'paid' ? new Date().toISOString() : null,
        payment_provider: 'payso',
        payment_ref: refNo,
        payment_approve_code: apprvcode || null
      })
      .eq('order_number', refNo)
      .select()
      .single();
    
    if (error) {
      console.error('PaySo webhook: Failed to update order:', error);
      return new Response('Failed to update order', { status: 500 });
    }
    
    if (paymentStatus === 'paid') {
      await supabaseAdmin.from('payments').insert({
        order_id: order.id,
        method: 'promptpay',
        amount: parseFloat(amt || '0'),
        status: 'completed',
        reference: refNo,
        metadata: { approve_code: apprvcode },
        paid_at: new Date().toISOString()
      });
      
      const { data: orderItems } = await supabaseAdmin
        .from('order_items')
        .select('product_id, quantity')
        .eq('order_id', order.id);
      
      for (const item of orderItems || []) {
        await supabaseAdmin.rpc('decrement_inventory', {
          product_id: item.product_id,
          quantity: item.quantity
        }).catch(err => {
          console.error('Failed to decrement inventory:', err);
        });
      }
      
      console.log(`PaySo webhook: Payment completed for order ${refNo}`);
    }
    
    return new Response('OK', { status: 200 });
    
  } catch (error) {
    console.error('PaySo webhook error:', error);
    return new Response('Internal error', { status: 500 });
  }
};
