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

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

// GET /api/admin/faqs/[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('faqs')
      .select('*')
      .eq('id', id)
      .single();
    
    if (error) {
      console.error('Error fetching faq:', error);
      return NextResponse.json(
        { error: '获取常见问题失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ faq: data });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}

// PUT /api/admin/faqs/[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 = upsertFaqSchema.parse(body);
    
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('faqs')
      .update({
        question: validated.question,
        answer: validated.answer,
        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 faq:', error);
      return NextResponse.json(
        { error: '更新常见问题失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ faq: data });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}

// DELETE /api/admin/faqs/[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('faqs')
      .delete()
      .eq('id', id);
    
    if (error) {
      console.error('Error deleting faq:', error);
      return NextResponse.json(
        { error: '删除常见问题失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
