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

// GET /api/faqs - 获取常见问题列表（公开）
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('faqs')
      .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 faqs:', error);
      // 如果表不存在，返回空数组
      if (error.code === '42P01' || error.code === 'PGRST205' || error.message?.includes('does not exist')) {
        return NextResponse.json({ faqs: [] });
      }
      return NextResponse.json(
        { error: '获取常见问题失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ faqs: data || [] });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
