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

// GET /api/content - 公开获取内容列表
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const contentType = searchParams.get('type');
    const contentId = searchParams.get('id');
    
    const client = getSupabaseClient();
    
    let query = client
      .from('site_content')
      .select('*')
      .eq('is_active', true)
      .order('sort_order', { ascending: true });
    
    if (contentType) {
      query = query.eq('content_type', contentType);
    }
    
    if (contentId) {
      query = query.eq('id', contentId);
    }
    
    const { data, error } = await query;
    
    if (error) {
      console.error('Error fetching content:', error);
      return NextResponse.json(
        { error: '获取内容失败' },
        { status: 500 }
      );
    }
    
    // 如果是单个内容请求
    if (contentId && data) {
      return NextResponse.json({ content: data[0] || null });
    }
    
    return NextResponse.json({ content: data });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
