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

export const POST: APIRoute = async ({ request }) => {
  try {
    const authHeader = request.headers.get('authorization');
    const token = getTokenFromHeader(authHeader);
    const payload = verifyToken(token || '');
    
    if (!payload) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { orderId } = await request.json();
    
    if (!orderId) {
      return new Response(JSON.stringify({ error: 'Order ID is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { data: order } = await supabaseAdmin
      .from('orders')
      .select('order_number, payment_status')
      .eq('id', orderId)
      .single();
    
    if (!order) {
      return new Response(JSON.stringify({ error: 'Order not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    if (order.user_id !== payload.userId && payload.role !== 'admin') {
      return new Response(JSON.stringify({ error: 'Access denied' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const payso = createPaySoClient();
    const result = await payso.inquiryOrder(order.order_number);
    
    let paymentStatus = order.payment_status;
    let orderStatus = null;
    
    if (result.status === 0 && result.data) {
      paymentStatus = 'paid';
      orderStatus = 'confirmed';
    }
    
    if (paymentStatus !== order.payment_status) {
      await supabaseAdmin
        .from('orders')
        .update({
          payment_status: paymentStatus,
          status: orderStatus || undefined,
          paid_at: paymentStatus === 'paid' ? new Date().toISOString() : undefined
        })
        .eq('id', orderId);
      
      if (paymentStatus === 'paid') {
        const { data: paymentOrder } = await supabaseAdmin
          .from('orders')
          .select('id, user_id, total')
          .eq('id', orderId)
          .single();
        
        if (paymentOrder) {
          await supabaseAdmin.from('payments').insert({
            order_id: paymentOrder.id,
            user_id: paymentOrder.user_id,
            method: 'promptpay',
            amount: paymentOrder.total,
            status: 'completed',
            reference: order.order_number,
            paid_at: new Date().toISOString()
          });
          
          const { data: orderItems } = await supabaseAdmin
            .from('order_items')
            .select('product_id, quantity')
            .eq('order_id', orderId);
          
          for (const item of orderItems || []) {
            await supabaseAdmin.rpc('decrement_inventory', {
              product_id: item.product_id,
              quantity: item.quantity
            });
          }
        }
      }
    }
    
    return new Response(JSON.stringify({
      success: true,
      orderNumber: order.order_number,
      paymentStatus,
      inquiryResult: result
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Payment inquiry error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
