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

function generateOrderNumber(): string {
  const timestamp = Date.now().toString(36).toUpperCase();
  const random = Math.random().toString(36).substring(2, 6).toUpperCase();
  return `ORD-${timestamp}${random}`;
}

function calculateTotals(items: Array<{ price: number; quantity: number }>) {
  const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
  const taxRate = 0.07;
  const tax = Math.round(subtotal * taxRate * 100) / 100;
  const shipping = subtotal >= 500 ? 0 : 50;
  const total = Math.round((subtotal + tax + shipping) * 100) / 100;
  
  return { subtotal, tax, shipping, total };
}

export const GET: APIRoute = async ({ request, url }) => {
  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 page = parseInt(url.searchParams.get('page') || '1');
    const limit = Math.min(parseInt(url.searchParams.get('limit') || '20'), 100);
    const status = url.searchParams.get('status');
    const from = (page - 1) * limit;
    const to = page * limit - 1;
    
    let query = supabase
      .from('orders')
      .select(`
        *,
        items:order_items(*, product:products(id, name, slug, images)),
        user:users(id, name, email)
      `, { count: 'exact' })
      .range(from, to)
      .order('created_at', { ascending: false });
    
    if (payload.role === 'customer') {
      query = query.eq('user_id', payload.userId);
    } else if (payload.role === 'vendor') {
      const { data: vendor } = await supabase
        .from('vendor_profiles')
        .select('id')
        .eq('user_id', payload.userId)
        .single();
      
      if (vendor) {
        query = query.eq('vendor_id', vendor.id);
      }
    }
    
    if (status) {
      query = query.eq('status', status);
    }
    
    const { data: orders, error, count } = await query;
    
    if (error) {
      throw error;
    }
    
    return new Response(JSON.stringify({
      success: true,
      orders: orders || [],
      pagination: {
        page,
        limit,
        total: count || 0,
        pages: Math.ceil((count || 0) / limit)
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Orders list error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

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 body = await request.json();
    const { items, shippingAddress } = body;
    
    if (!items || !Array.isArray(items) || items.length === 0) {
      return new Response(JSON.stringify({ error: 'Order items are required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    if (!shippingAddress || !shippingAddress.name || !shippingAddress.phone || !shippingAddress.address) {
      return new Response(JSON.stringify({ error: 'Complete shipping address is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const amounts = items.map((item: any) => ({
      price: item.price,
      quantity: item.quantity
    }));
    
    const { subtotal, tax, shipping, total } = calculateTotals(amounts);
    
    const orderNumber = generateOrderNumber();
    
    const { data: order, error: orderError } = await supabaseAdmin
      .from('orders')
      .insert({
        order_number: orderNumber,
        user_id: payload.userId,
        subtotal,
        tax,
        shipping_cost: shipping,
        total,
        shipping_name: shippingAddress.name,
        shipping_phone: shippingAddress.phone,
        shipping_address: shippingAddress.address,
        shipping_city: shippingAddress.city || null,
        shipping_province: shippingAddress.province || null,
        shipping_postal_code: shippingAddress.postal_code || null,
        status: 'pending',
        payment_status: 'pending'
      })
      .select()
      .single();
    
    if (orderError) {
      throw orderError;
    }
    
    const orderItems = items.map((item: any) => ({
      order_id: order.id,
      product_id: item.productId,
      product_name: item.name || 'Product',
      product_image: item.image || null,
      price: item.price,
      quantity: item.quantity,
      total: item.price * item.quantity
    }));
    
    const { error: itemsError } = await supabaseAdmin
      .from('order_items')
      .insert(orderItems);
    
    if (itemsError) {
      throw itemsError;
    }
    
    return new Response(JSON.stringify({
      success: true,
      order,
      totals: { subtotal, tax, shipping, total }
    }), {
      status: 201,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Create order error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
