import type { APIRoute } from 'astro';
import { supabase } from '../../../../lib/supabase';

export const GET: APIRoute = async ({ params }) => {
  try {
    const { slug } = params;
    
    if (!slug) {
      return new Response(JSON.stringify({ error: 'Vendor slug is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { data: vendor, error } = await supabase
      .from('vendor_profiles')
      .select(`
        *,
        user:users(id, name, avatar_url)
      `)
      .eq('store_slug', slug)
      .eq('payout_status', 'approved')
      .single();
    
    if (error || !vendor) {
      return new Response(JSON.stringify({ error: 'Vendor not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const { data: products, count } = await supabase
      .from('products')
      .select('*', { count: 'exact' })
      .eq('vendor_id', vendor.id)
      .eq('status', 'active')
      .order('created_at', { ascending: false })
      .limit(20);
    
    return new Response(JSON.stringify({
      success: true,
      vendor: {
        ...vendor,
        products_count: count || 0
      },
      products: products || []
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Get vendor error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
