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

export const GET: APIRoute = async ({ url }) => {
  try {
    const parentOnly = url.searchParams.get('parent') !== 'false';
    
    let query = supabase
      .from('categories')
      .select('*')
      .eq('is_active', true)
      .order('sort_order', { ascending: true });
    
    if (parentOnly) {
      query = query.is('parent_id', null);
    }
    
    const { data: categories, error } = await query;
    
    if (error) {
      throw error;
    }
    
    return new Response(JSON.stringify({
      success: true,
      categories: categories || []
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {
    console.error('Categories list error:', error);
    return new Response(JSON.stringify({
      error: error instanceof Error ? error.message : 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
