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

export const POST: APIRoute = async ({ request, redirect }) => {
  try {
    const contentType = request.headers.get('content-type');
    
    if (contentType?.includes('application/json')) {
      const body = await request.json();
      return handleCallback(body);
    }
    
    const url = new URL(request.url);
    const refNo = url.searchParams.get('refno');
    const status = url.searchParams.get('status');
    const amt = url.searchParams.get('amt');
    
    if (status && isPaymentSuccess(status)) {
      return redirect(`/orders/success?refno=${refNo}&amt=${amt}`, 302);
    } else if (isPaymentPending(status || '')) {
      return redirect(`/orders/pending?refno=${refNo}`, 302);
    } else {
      return redirect(`/orders/failed?refno=${refNo}`, 302);
    }
    
  } catch (error) {
    console.error('Payment callback error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

async function handleCallback(data: any) {
  const { refno, status, amt, apprvcode } = data;
  
  if (!refno) {
    return new Response(JSON.stringify({ error: 'Missing refno' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' }
    });
  }
  
  return new Response(JSON.stringify({
    success: true,
    refno,
    status,
    message: isPaymentSuccess(status) ? 'Payment successful' : 'Payment pending'
  }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  });
}

export const GET: APIRoute = async ({ request }) => {
  const url = new URL(request.url);
  const refNo = url.searchParams.get('refno');
  
  if (!refNo) {
    return new Response(JSON.stringify({ error: 'Missing refno' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' }
    });
  }
  
  const payso = createPaySoClient();
  const result = await payso.inquiryOrder(refNo);
  
  return new Response(JSON.stringify({
    success: true,
    result
  }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  });
};
