"use server";

import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/db";
import { env } from "@/lib/env";
import { hashPassword, verifyPassword, checkPasswordPolicy, dummyVerifyDigest } from "@/lib/auth/password";
import {
  createSession,
  destroySession,
  setSessionCookie,
  clearSessionCookie,
} from "@/lib/auth/session";
import { loginSchema, registerSchema, fieldErrors } from "@/lib/validation";
import { recordAudit, recentFailedLogins, recordFailedLogin } from "@/lib/audit";
import { actionError, type ActionState } from "@/lib/action-state";

/**
 * Authentication server actions.
 *
 * Sign-in is by USERNAME, never email. Failed attempts are audited and throttled
 * per-username; the error message is deliberately identical for "unknown user"
 * and "wrong password" so the endpoint cannot be used to enumerate accounts.
 */

/**
 * Only allow same-origin relative paths as post-login redirect targets.
 *
 * The `//host` check alone is not enough. Browsers normalise backslashes to
 * forward slashes when resolving a `Location` header, so `/\evil.com` — which
 * passes a naive `startsWith("/") && !startsWith("//")` test — is resolved as
 * `//evil.com`, i.e. `https://evil.com`. Any backslash, and any character a
 * browser may strip or fold (tab, newline, CR), disqualifies the value. A
 * single leading slash followed by an ordinary path is the only accepted shape.
 */
function safeRedirectTarget(next: string | undefined, fallback: string): string {
  if (!next) return fallback;
  if (!next.startsWith("/")) return fallback;
  if (next.startsWith("//") || next.startsWith("/\\")) return fallback;
  // Control characters and backslashes can be folded into a scheme-relative
  // URL by the browser; refuse them outright.
  if (/[\\\u0000-\u001f\u007f]/.test(next)) return fallback;
  return next;
}

const GENERIC_CREDENTIAL_ERROR = "Username atau password salah.";

export async function loginAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  const parsed = loginSchema.safeParse({
    username: formData.get("username"),
    password: formData.get("password"),
    next: formData.get("next") ?? undefined,
  });

  if (!parsed.success) {
    return actionError("Periksa kembali data yang kamu masukkan.", fieldErrors(parsed.error));
  }

  const { username, password, next } = parsed.data;

  const failures = await recentFailedLogins(username, env.AUTH_LOCKOUT_MINUTES);
  if (failures >= env.AUTH_MAX_LOGIN_ATTEMPTS) {
    await recordAudit({
      action: "LOGIN_THROTTLED",
      entity: "User",
      entityId: username.toLowerCase(),
    });
    return actionError(
      `Terlalu banyak percobaan masuk. Coba lagi dalam ${env.AUTH_LOCKOUT_MINUTES} menit.`
    );
  }

  const user = await prisma.user.findUnique({
    where: { username },
    select: { id: true, username: true, passwordHash: true, role: true, status: true },
  });

  // Always run a verification to keep response timing uniform whether or not
  // the username exists. The digest must be a *real* Argon2id hash: a
  // hand-written placeholder is rejected during decoding and returns far
  // faster than a genuine account, which is a username-enumeration oracle.
  const passwordValid = user
    ? await verifyPassword(password, user.passwordHash)
    : await verifyPassword(password, await dummyVerifyDigest());

  if (!user || !passwordValid) {
    await recordFailedLogin(username, user ? "bad_password" : "unknown_user");
    return actionError(GENERIC_CREDENTIAL_ERROR);
  }

  if (user.status === "SUSPENDED") {
    await recordAudit({ actorId: user.id, action: "LOGIN_BLOCKED_SUSPENDED", entity: "User", entityId: user.id });
    return actionError("Akun ini ditangguhkan. Hubungi administrator sekolah.");
  }

  if (user.status === "PENDING") {
    return actionError("Akun ini belum diaktifkan. Hubungi administrator sekolah.");
  }

  const session = await createSession(user.id);
  await setSessionCookie(session.token, session.expiresAt);

  await recordAudit({
    actorId: user.id,
    action: "LOGIN_SUCCESS",
    entity: "User",
    entityId: user.id,
    metadata: { username: user.username, role: user.role },
  });

  redirect(safeRedirectTarget(next, "/dashboard"));
}

export async function registerAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  const parsed = registerSchema.safeParse({
    username: formData.get("username"),
    fullName: formData.get("fullName"),
    email: formData.get("email") ?? "",
    password: formData.get("password"),
    role: formData.get("role") ?? "STUDENT",
    joinCode: formData.get("joinCode") ?? undefined,
  });

  if (!parsed.success) {
    return actionError("Periksa kembali data yang kamu masukkan.", fieldErrors(parsed.error));
  }

  const { username, fullName, email, password, role, joinCode } = parsed.data;

  const policy = checkPasswordPolicy(password);
  if (!policy.ok) {
    return actionError("Password belum memenuhi syarat.", { password: policy.errors[0] });
  }

  const existing = await prisma.user.findFirst({
    where: { OR: [{ username }, ...(email ? [{ email }] : [])] },
    select: { username: true, email: true },
  });

  if (existing) {
    const errors: Record<string, string> = {};
    if (existing.username === username) errors.username = "Username sudah digunakan.";
    if (email && existing.email === email) errors.email = "Email sudah terdaftar.";
    return actionError("Pendaftaran gagal karena data sudah terpakai.", errors);
  }

  // Students may optionally join a class immediately with a join code.
  let classroomId: string | null = null;
  if (joinCode) {
    const classroom = await prisma.classroom.findUnique({
      where: { joinCode: joinCode.toUpperCase() },
      select: { id: true },
    });
    if (!classroom) {
      return actionError("Kode kelas tidak ditemukan.", { joinCode: "Kode kelas tidak valid." });
    }
    classroomId = classroom.id;
  }

  const passwordHash = await hashPassword(password);

  // A teacher account grants access to every student's grades, submissions and
  // contact details, so it cannot be created by an anonymous visitor. Self
  // registration is open to students only; a teacher applicant is stored as
  // PENDING — the login flow already refuses PENDING accounts — and an
  // administrator activates them from the users console. Creating the row
  // rather than rejecting it keeps the request on file for review.
  const wantsTeacher = role === "TEACHER";
  const accountStatus = wantsTeacher ? "PENDING" : "ACTIVE";

  const user = await prisma.$transaction(async (tx) => {
    const created = await tx.user.create({
      data: {
        username,
        passwordHash,
        fullName,
        email: email || null,
        role,
        status: accountStatus,
      },
      select: { id: true, username: true, role: true },
    });

    if (classroomId) {
      await tx.classEnrollment.create({
        data: { classId: classroomId, studentId: created.id, status: "ACTIVE" },
      });
    }

    await tx.notification.create({
      data: {
        userId: created.id,
        type: "SUCCESS",
        title: "Selamat datang di RoboLearn!",
        body: "Akunmu berhasil dibuat. Mulai jelajahi kursus yang tersedia.",
        link: "/dashboard/courses",
      },
    });

    return created;
  });

  await recordAudit({
    actorId: user.id,
    action: "USER_REGISTERED",
    entity: "User",
    entityId: user.id,
    metadata: { username: user.username, role: user.role, joinedClass: Boolean(classroomId) },
  });

  // A pending teacher must not be handed a session — that is the whole point of
  // the gate. Students are signed in immediately as before.
  if (wantsTeacher) {
    return actionError(
      "Pendaftaran guru berhasil dikirim. Akunmu menunggu persetujuan administrator sebelum bisa digunakan."
    );
  }

  const session = await createSession(user.id);
  await setSessionCookie(session.token, session.expiresAt);

  redirect("/dashboard");
}

export async function logoutAction(): Promise<void> {
  const store = await cookies();
  const token = store.get(env.AUTH_COOKIE_NAME)?.value;

  await destroySession(token);
  await clearSessionCookie();

  await recordAudit({ action: "LOGOUT", entity: "Session" });

  redirect("/login");
}
