import { randomBytes, timingSafeEqual } from "node:crypto";
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { hashPassword } from "@/lib/auth";
import { ensureSeed } from "@/lib/seed";
import { handleApiError } from "@/lib/api-helpers";

function validSetupKey(candidate: unknown): boolean {
  const expected = process.env.INITIAL_SETUP_KEY;
  if (typeof candidate !== "string" || !expected || expected.length < 32) return false;
  const providedBuffer = Buffer.from(candidate);
  const expectedBuffer = Buffer.from(expected);
  return providedBuffer.length === expectedBuffer.length && timingSafeEqual(providedBuffer, expectedBuffer);
}

export async function POST(req: NextRequest) {
  try {
    if (!process.env.INITIAL_SETUP_KEY || process.env.INITIAL_SETUP_KEY.length < 32) {
      return NextResponse.json({ error: "إعداد إنشاء المدير غير مكتمل على الخادم" }, { status: 503 });
    }

    const body = (await req.json()) as {
      setupKey?: unknown;
      username?: unknown;
      password?: unknown;
      confirmPassword?: unknown;
      phone?: unknown;
    };
    if (!validSetupKey(body.setupKey)) {
      return NextResponse.json({ error: "مفتاح الإعداد غير صحيح" }, { status: 403 });
    }

    const username = typeof body.username === "string" ? body.username.trim().toLowerCase() : "";
    const password = typeof body.password === "string" ? body.password : "";
    if (!/^[a-z0-9_.-]{3,32}$/.test(username)) {
      return NextResponse.json({ error: "اسم المستخدم يجب أن يكون 3 إلى 32 حرفًا إنجليزيًا أو رقمًا" }, { status: 400 });
    }
    if (password.length < 12 || Buffer.byteLength(password, "utf8") > 72) {
      return NextResponse.json({ error: "كلمة المرور يجب أن تكون 12 حرفًا على الأقل وبحد أقصى 72 بايتًا" }, { status: 400 });
    }
    if (password !== body.confirmPassword) {
      return NextResponse.json({ error: "تأكيد كلمة المرور غير مطابق" }, { status: 400 });
    }
    const phone = normalizePhone(body.phone);
    if (!phone) return NextResponse.json({ error: "أدخل رقم هاتف صحيحاً (7 إلى 15 رقماً)" }, { status: 400 });

    await ensureSeed();
    const passwordHash = await hashPassword(password);
    const recoveryCode = randomBytes(16).toString("hex").toUpperCase();
    const recoveryCodeHash = await hashPassword(recoveryCode);
    const result = await db.$transaction(async (tx) => {
      if (await tx.user.count() !== 0) return false;
      const user = await tx.user.create({
        data: {
          username,
          passwordHash,
          fullName: "مدير النظام",
          phone,
          recoveryCodeHash,
          role: "SUPER_ADMIN",
          schoolId: null,
        },
      });
      await tx.auditLog.create({
        data: {
          action: "SETUP",
          entity: "User",
          entityId: user.id,
          details: "إنشاء أول مدير للنظام من معالج الإعداد الأولي",
          userName: username,
        },
      });
      return true;
    });

    if (!result) {
      return NextResponse.json({ error: "تم إنشاء مدير النظام مسبقًا. انتقل إلى تسجيل الدخول." }, { status: 409 });
    }
    return NextResponse.json({ success: true, username, recoveryCode });
  } catch (err) {
    return handleApiError(err);
  }
}

function normalizePhone(value: unknown): string | null {
  const phone = typeof value === "string" ? value.replace(/[\s()-]/g, "") : "";
  return /^\+?[0-9]{7,15}$/.test(phone) ? phone : null;
}
