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 - 获取所有案例（管理员）
export async function GET(request: NextRequest) {
  try {
    const adminId = await verifyAdmin();
    if (!adminId) {
      return NextResponse.json(
        { error: '请先登录' },
        { status: 401 }
      );
    }
    
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('cases')
      .select('*')
      .order('sort_order', { ascending: true })
      .order('created_at', { ascending: false });
    
    if (error) {
      console.error('Error fetching cases:', error);
      // 如果表不存在，返回空数组
      if (error.code === '42P01' || error.code === 'PGRST205' || error.message?.includes('does not exist')) {
        return NextResponse.json({ cases: [] });
      }
      return NextResponse.json(
        { error: '获取案例失败' },
        { status: 500 }
      );
    }
    
    // 解析images字段
    const cases = (data || []).map(item => ({
      ...item,
      images: JSON.parse(item.images || '[]')
    }));
    
    return NextResponse.json({ cases });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}

// POST /api/admin/cases - 创建案例
export async function POST(request: NextRequest) {
  try {
    const adminId = await verifyAdmin();
    if (!adminId) {
      return NextResponse.json(
        { error: '请先登录' },
        { status: 401 }
      );
    }
    
    const body = await request.json();
    
    // 验证必填字段
    if (!body.title || !body.title.trim()) {
      return NextResponse.json(
        { error: '标题不能为空' },
        { status: 400 }
      );
    }
    if (!body.images || !Array.isArray(body.images) || body.images.length === 0) {
      return NextResponse.json(
        { error: '至少上传一张图片' },
        { status: 400 }
      );
    }
    
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('cases')
      .insert({
        title: body.title.trim(),
        description: body.description || null,
        images: JSON.stringify(body.images),
        category: body.category || null,
        sort_order: body.sortOrder || 0,
        is_active: body.isActive ?? true,
      })
      .select()
      .single();
    
    if (error) {
      console.error('Error creating case:', error);
      // 如果表不存在
      if (error.code === '42P01' || error.code === 'PGRST205') {
        return NextResponse.json(
          { error: '数据库表不存在，请先初始化数据库', code: error.code },
          { status: 500 }
        );
      }
      return NextResponse.json(
        { error: '创建案例失败: ' + error.message, code: error.code },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ 
      case: {
        ...data,
        images: JSON.parse(data.images || '[]')
      }
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误: ' + String(error) },
      { status: 500 }
    );
  }
}
