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

// GET /api/admin/content - 获取内容列表
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const contentType = searchParams.get('type');
    
    const client = getSupabaseClient();
    
    let query = client
      .from('site_content')
      .select('*')
      .order('sort_order', { ascending: true });
    
    if (contentType) {
      query = query.eq('content_type', contentType);
    }
    
    const { data, error } = await query;
    
    if (error) {
      console.error('Error fetching content:', error);
      return NextResponse.json(
        { error: '获取内容失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ content: data });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}

// POST /api/admin/content - 创建新内容
export async function POST(request: NextRequest) {
  try {
    // 验证管理员身份
    const cookieStore = await cookies();
    const adminId = cookieStore.get('admin_id')?.value;
    
    if (!adminId) {
      return NextResponse.json(
        { error: '未授权' },
        { status: 401 }
      );
    }
    
    const body = await request.json();
    const { id, contentType, title, description, content, icon, category, sortOrder, isActive, coverImage, attachments } = body;
    
    if (!id || !contentType || !title) {
      return NextResponse.json(
        { error: '缺少必要参数' },
        { status: 400 }
      );
    }
    
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('site_content')
      .insert({
        id,
        content_type: contentType,
        title,
        description: description || null,
        content: content || null,
        icon: icon || null,
        category: category || null,
        sort_order: sortOrder || 0,
        is_active: isActive !== undefined ? isActive : true,
        cover_image: coverImage || null,
        attachments: attachments || null,
      })
      .select()
      .single();
    
    if (error) {
      console.error('Error creating content:', error);
      return NextResponse.json(
        { error: '创建失败', details: error.message },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ success: true, content: data });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
