import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { verifyPassword, setSessionCookie } from "@/lib/auth";
import { logAudit } from "@/lib/audit";
import { ensureSeed } from "@/lib/seed";
import { handleApiError } from "@/lib/api-helpers";

const loginAttempts = new Map<string, { count: number; startedAt: number }>();
const LOGIN_WINDOW_MS = 15 * 60 * 1000;
const LOGIN_MAX_ATTEMPTS = 8;

export async function POST(req: NextRequest) {
  try {
    await ensureSeed();
    const body = await req.json();
    const { username, password } = body as { username?: string; password?: string };
    if (!username || !password) {
      return NextResponse.json({ error: "يرجى إدخال اسم المستخدم وكلمة المرور" }, { status: 400 });
    }
    const attemptKey = `${req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "local"}:${username.trim().toLowerCase()}`;
    const now = Date.now();
    const prior = loginAttempts.get(attemptKey);
    if (prior && now - prior.startedAt < LOGIN_WINDOW_MS && prior.count >= LOGIN_MAX_ATTEMPTS) {
      return NextResponse.json({ error: "محاولات كثيرة. انتظر 15 دقيقة ثم حاول مجدداً" }, { status: 429 });
    }
    const user = await db.user.findUnique({ where: { username: username.trim() } });
    if (!user || !(await verifyPassword(password, user.passwordHash))) {
      if (!prior || now - prior.startedAt >= LOGIN_WINDOW_MS) loginAttempts.set(attemptKey, { count: 1, startedAt: now });
      else loginAttempts.set(attemptKey, { ...prior, count: prior.count + 1 });
      await logAudit(null, {
        action: "LOGIN_FAILED",
        entity: "Auth",
        details: `محاولة دخول فاشلة باسم المستخدم: ${username}`,
      });
      return NextResponse.json({ error: "اسم المستخدم أو كلمة المرور غير صحيحة" }, { status: 401 });
    }
    if (!user.isActive) {
      return NextResponse.json({ error: "هذا الحساب معطّل - راجع مدير النظام" }, { status: 403 });
    }
    loginAttempts.delete(attemptKey);
    let allowedViews: string[] | null = null;
    if (user.allowedViews) {
      try {
        const parsed = JSON.parse(user.allowedViews);
        if (Array.isArray(parsed)) allowedViews = parsed as string[];
      } catch {
        allowedViews = null;
      }
    }
    const sessionUser = {
      id: user.id,
      username: user.username,
      fullName: user.fullName,
      role: user.role as "SUPER_ADMIN" | "ADMIN" | "ACCOUNTANT" | "STAFF",
      schoolId: user.schoolId ?? null,
      allowedViews,
    };
    await setSessionCookie(sessionUser);
    await logAudit(sessionUser, {
      action: "LOGIN",
      entity: "Auth",
      entityId: user.id,
      details: `تسجيل دخول ناجح للمستخدم ${user.fullName}`,
    });
    return NextResponse.json({ user: sessionUser });
  } catch (err) {
    return handleApiError(err);
  }
}
