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

// GET /api/admin/content/[id] - 获取单个内容
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('site_content')
      .select('*')
      .eq('id', id)
      .single();
    
    if (error || !data) {
      return NextResponse.json(
        { error: '内容不存在' },
        { status: 404 }
      );
    }
    
    return NextResponse.json({ content: data });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}

// PUT /api/admin/content/[id] - 更新内容
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    
    // 验证管理员身份
    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 { title, description, content, icon, category, sortOrder, isActive, coverImage, attachments } = body;
    
    const client = getSupabaseClient();
    
    const updateData: Record<string, unknown> = { updated_at: new Date().toISOString() };
    if (title !== undefined) updateData.title = title;
    if (description !== undefined) updateData.description = description;
    if (content !== undefined) updateData.content = content;
    if (icon !== undefined) updateData.icon = icon;
    if (category !== undefined) updateData.category = category;
    if (sortOrder !== undefined) updateData.sort_order = sortOrder;
    if (isActive !== undefined) updateData.is_active = isActive;
    if (coverImage !== undefined) updateData.cover_image = coverImage;
    if (attachments !== undefined) updateData.attachments = attachments;
    
    const { data, error } = await client
      .from('site_content')
      .update(updateData)
      .eq('id', id)
      .select()
      .single();
    
    if (error) {
      console.error('Error updating 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 }
    );
  }
}

// DELETE /api/admin/content/[id] - 删除内容
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    
    // 验证管理员身份
    const cookieStore = await cookies();
    const adminId = cookieStore.get('admin_id')?.value;
    
    if (!adminId) {
      return NextResponse.json(
        { error: '未授权' },
        { status: 401 }
      );
    }
    
    const client = getSupabaseClient();
    
    const { error } = await client
      .from('site_content')
      .delete()
      .eq('id', id);
    
    if (error) {
      console.error('Error deleting content:', error);
      return NextResponse.json(
        { error: '删除失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
