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 - 获取所有常见问题（管理员）
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('faqs')
      .select('*')
      .order('sort_order', { ascending: true })
      .order('created_at', { ascending: false });
    
    if (error) {
      console.error('Error fetching faqs:', error);
      // 如果表不存在，返回空数组
      if (error.code === '42P01' || error.code === 'PGRST205' || error.message?.includes('does not exist')) {
        return NextResponse.json({ faqs: [] });
      }
      return NextResponse.json(
        { error: '获取常见问题失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ faqs: data || [] });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}

// POST /api/admin/faqs - 创建常见问题
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.question || !body.question.trim()) {
      return NextResponse.json(
        { error: '问题不能为空' },
        { status: 400 }
      );
    }
    if (!body.answer || !body.answer.trim()) {
      return NextResponse.json(
        { error: '答案不能为空' },
        { status: 400 }
      );
    }
    
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('faqs')
      .insert({
        question: body.question.trim(),
        answer: body.answer.trim(),
        category: body.category || null,
        sort_order: body.sortOrder || 0,
        is_active: body.isActive ?? true,
      })
      .select()
      .single();
    
    if (error) {
      console.error('Error creating faq:', 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({ faq: data });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误: ' + String(error) },
      { status: 500 }
    );
  }
}
