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

export const GET: APIRoute = async ({ url }) => {
  try {
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = Math.min(parseInt(url.searchParams.get('limit') || '20'), 100);
    const search = url.searchParams.get('search');
    
    const from = (page - 1) * limit;
    const to = page * limit - 1;
    
    let query = supabase
      .from('vendor_profiles')
      .select(`
        *,
        user:users(id, name, avatar_url, email)
      `, { count: 'exact' })
      .eq('payout_status', 'approved')
      .range(from, to);
    
    if (search) {
      query = query.or(`store_name.ilike.%${search}%,store_description.ilike.%${search}%`);
    }
    
    query = query.order('created_at', { ascending: false });
    
    const { data: vendors, error, count } = await query;
    
    if (error) {
      throw error;
    }
    
    return new Response(JSON.stringify({
      success: true,
      vendors: vendors || [],
      pagination: {
        page,
        limit,
        total: count || 0,
        pages: Math.ceil((count || 0) / limit)
      }
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Vendors list error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
