import { NextRequest, NextResponse } from 'next/server';
import { randomUUID } from 'crypto';
import bcrypt from 'bcryptjs';
import { query } from '@/lib/db';
export const runtime = 'nodejs';
export async function POST(req: NextRequest) {
  try {
    const setupKey = req.headers.get('x-setup-key');
    if (!process.env.SETUP_KEY || setupKey !== process.env.SETUP_KEY) return NextResponse.json({ error: 'غير مصرح' }, { status: 403 });
    const existing = await query<any>("SELECT id FROM users WHERE role = 'super_admin' LIMIT 1");
    if (existing.length) return NextResponse.json({ error: 'تم إنشاء المدير بالفعل. أغلق إعداد المدير من ملف البيئة.' }, { status: 409 });
    const { full_name, email, password } = await req.json();
    if (!full_name || !email || typeof password !== 'string' || password.length < 12) return NextResponse.json({ error: 'الاسم والبريد مطلوبان وكلمة المرور 12 حرفًا على الأقل' }, { status: 400 });
    const id = randomUUID();
    const hash = await bcrypt.hash(password, 12);
    await query('INSERT INTO users (id, full_name, email, password_hash, role) VALUES (?, ?, ?, ?, \'super_admin\')', [id, String(full_name).trim(), String(email).trim().toLowerCase(), hash]);
    return NextResponse.json({ ok: true, message: 'تم إنشاء حساب المدير. احذف SETUP_KEY أو غيّره فورًا.' });
  } catch (e) { console.error(e); return NextResponse.json({ error: 'فشل إنشاء المدير؛ تحقق من إعدادات MySQL وعدم تكرار البريد.' }, { status: 500 }); }
}
