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

// 验证管理员身份
async function verifyAdmin() {
  const cookieStore = await cookies();
  const adminId = cookieStore.get('admin_id')?.value;
  return adminId;
}

// GET /api/admin/cases/[id] - 获取单个案例
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const adminId = await verifyAdmin();
    if (!adminId) {
      return NextResponse.json(
        { error: '请先登录' },
        { status: 401 }
      );
    }
    
    const { id } = await params;
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('cases')
      .select('*')
      .eq('id', id)
      .single();
    
    if (error) {
      console.error('Error fetching case:', error);
      return NextResponse.json(
        { error: '获取案例失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ 
      case: {
        ...data,
        images: JSON.parse(data.images || '[]')
      }
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}

// PUT /api/admin/cases/[id] - 更新案例
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const adminId = await verifyAdmin();
    if (!adminId) {
      return NextResponse.json(
        { error: '请先登录' },
        { status: 401 }
      );
    }
    
    const { id } = await params;
    const body = await request.json();
    const validated = upsertCaseSchema.parse(body);
    
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('cases')
      .update({
        title: validated.title,
        description: validated.description || null,
        images: JSON.stringify(validated.images),
        category: validated.category || null,
        sort_order: validated.sortOrder || 0,
        is_active: validated.isActive ?? true,
        updated_at: new Date().toISOString(),
      })
      .eq('id', id)
      .select()
      .single();
    
    if (error) {
      console.error('Error updating case:', error);
      return NextResponse.json(
        { error: '更新案例失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ 
      case: {
        ...data,
        images: JSON.parse(data.images || '[]')
      }
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}

// DELETE /api/admin/cases/[id] - 删除案例
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const adminId = await verifyAdmin();
    if (!adminId) {
      return NextResponse.json(
        { error: '请先登录' },
        { status: 401 }
      );
    }
    
    const { id } = await params;
    const client = getSupabaseClient();
    
    const { error } = await client
      .from('cases')
      .delete()
      .eq('id', id);
    
    if (error) {
      console.error('Error deleting case:', error);
      return NextResponse.json(
        { error: '删除案例失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
