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

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

// POST /api/admin/faqs/batch - 批量导入常见问题
export async function POST(request: NextRequest) {
  try {
    const adminId = await verifyAdmin();
    if (!adminId) {
      return NextResponse.json(
        { error: '请先登录' },
        { status: 401 }
      );
    }
    
    const body = await request.json();
    const { faqs } = body;
    
    if (!Array.isArray(faqs) || faqs.length === 0) {
      return NextResponse.json(
        { error: '请提供要导入的问题列表' },
        { status: 400 }
      );
    }
    
    const client = getSupabaseClient();
    
    // 准备插入数据
    const insertData = faqs.map((faq, index) => ({
      question: faq.question,
      answer: faq.answer,
      category: faq.category || null,
      sort_order: faq.sortOrder || index + 1,
      is_active: true,
    }));
    
    // 批量插入
    const { data, error } = await client
      .from('faqs')
      .insert(insertData)
      .select();
    
    if (error) {
      console.error('Error importing faqs:', error);
      // 如果表不存在
      if (error.code === '42P01' || error.code === 'PGRST205') {
        return NextResponse.json(
          { error: '数据库表不存在，请先执行数据库初始化脚本' },
          { status: 500 }
        );
      }
      return NextResponse.json(
        { error: '导入失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ 
      success: true,
      imported: data?.length || 0 
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
