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

// PATCH /api/admin/customers/[id]/admin - 更新客户管理员状态
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    
    // 验证管理员身份
    const cookieStore = await cookies();
    const adminId = cookieStore.get('admin_id')?.value;
    const adminRole = cookieStore.get('admin_role')?.value;
    
    if (!adminId) {
      return NextResponse.json(
        { error: '未授权' },
        { status: 401 }
      );
    }
    
    // 只有 super_admin 可以设置管理员
    if (adminRole !== 'super_admin') {
      return NextResponse.json(
        { error: '权限不足，只有超级管理员可以设置用户为管理员' },
        { status: 403 }
      );
    }
    
    const body = await request.json();
    const { isAdmin } = body;
    
    if (typeof isAdmin !== 'boolean') {
      return NextResponse.json(
        { error: '无效的参数' },
        { status: 400 }
      );
    }
    
    const client = getSupabaseClient();
    
    const { data, error } = await client
      .from('customers')
      .update({ is_admin: isAdmin })
      .eq('id', id)
      .select()
      .single();
    
    if (error) {
      console.error('Error updating customer admin status:', error);
      return NextResponse.json(
        { error: '更新失败' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({
      success: true,
      customer: data,
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
