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

export const GET: 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' }
      });
    }
    
    if (payload.role !== 'vendor' && payload.role !== 'admin') {
      return new Response(JSON.stringify({ error: 'Only vendors can access dashboard' }), {
        status: 403,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { data: vendor } = await supabaseAdmin
      .from('vendor_profiles')
      .select('*')
      .eq('user_id', payload.userId)
      .single();
    
    if (!vendor) {
      return new Response(JSON.stringify({ error: 'Vendor profile not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { count: productsCount } = await supabaseAdmin
      .from('products')
      .select('*', { count: 'exact', head: true })
      .eq('vendor_id', vendor.id);
    
    const { data: ordersData } = await supabaseAdmin
      .from('orders')
      .select('total, status, payment_status')
      .eq('vendor_id', vendor.id);
    
    const orders = ordersData || [];
    const ordersCount = orders.length;
    
    let totalSales = 0;
    let pendingOrders = 0;
    let paidOrders = 0;
    let unpaidOrders = 0;
    
    for (const order of orders) {
      if (order.payment_status === 'paid') {
        totalSales += order.total;
        paidOrders++;
      } else if (order.payment_status !== 'paid') {
        unpaidOrders++;
      }
      
      if (order.status === 'pending' || order.status === 'confirmed' || order.status === 'processing') {
        pendingOrders++;
      }
    }
    
    const { data: recentOrders } = await supabaseAdmin
      .from('orders')
      .select(`
        id, order_number, total, status, payment_status, created_at,
        user:users(name, email),
        items:order_items(product_name, quantity, price)
      `)
      .eq('vendor_id', vendor.id)
      .order('created_at', { ascending: false })
      .limit(10);
    
    const { data: recentProducts } = await supabaseAdmin
      .from('products')
      .select('id, name, slug, images, price, inventory, status')
      .eq('vendor_id', vendor.id)
      .order('created_at', { ascending: false })
      .limit(10);
    
    return new Response(JSON.stringify({
      success: true,
      vendor,
      stats: {
        products: productsCount || 0,
        orders: ordersCount,
        totalSales: Math.round(totalSales * 100) / 100,
        pendingOrders,
        paidOrders,
        unpaidOrders
      },
      recentOrders: recentOrders || [],
      recentProducts: recentProducts || []
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Vendor dashboard error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
