import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseClient } from '@/storage/database/supabase-client';

// GET /api/cases - 获取案例列表（公开）
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const category = searchParams.get('category');
    
    const client = getSupabaseClient();
    
    let query = client
      .from('cases')
      .select('*')
      .eq('is_active', true)
      .order('sort_order', { ascending: true })
      .order('created_at', { ascending: false });
    
    if (category) {
      query = query.eq('category', category);
    }
    
    const { data, error } = await query;
    
    if (error) {
      console.error('Error fetching cases:', error);
      // 如果表不存在，返回空数组
      if (error.code === '42P01' || error.code === 'PGRST205' || error.message?.includes('does not exist')) {
        return NextResponse.json({ cases: [] });
      }
      return NextResponse.json(
        { error: '获取案例失败' },
        { status: 500 }
      );
    }
    
    // 解析images字段
    const cases = (data || []).map(item => ({
      ...item,
      images: JSON.parse(item.images || '[]')
    }));
    
    return NextResponse.json({ cases });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
