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, method = 'promptpay' } = 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('*, items:order_items(*, product:products(name))')
      .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' }
      });
    }
    
    if (order.payment_status === 'paid') {
      return new Response(JSON.stringify({ error: 'Order already paid' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { data: user } = await supabaseAdmin
      .from('users')
      .select('email')
      .eq('id', order.user_id)
      .single();
    
    const payso = createPaySoClient();
    
    const productDetail = order.items
      .map((item: any) => item.product?.name)
      .filter(Boolean)
      .join(', ')
      .substring(0, 200) || 'Order Payment';
    
    const returnUrl = `${import.meta.env.SITE_URL || 'http://localhost:4321'}/orders/${order.id}/success`;
    const callbackUrl = `${import.meta.env.SITE_URL || 'http://localhost:4321'}/api/webhooks/payso`;
    
    const paymentUrl = payso.createPaymentUrl({
      refno: order.order_number,
      customeremail: user?.email || 'customer@example.com',
      productdetail: productDetail,
      total: order.total,
      returnUrl,
      callbackUrl
    });
    
    await supabaseAdmin
      .from('orders')
      .update({
        payment_provider: 'payso',
        payment_method: method
      })
      .eq('id', orderId);
    
    return new Response(JSON.stringify({
      success: true,
      paymentUrl,
      orderNumber: order.order_number,
      paymentMethod: method
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Create payment error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
