"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/db";
import { authorize } from "@/lib/auth/rbac";
import { hashPassword, verifyPassword } from "@/lib/auth/password";
import { destroyAllSessionsForUser } from "@/lib/auth/session";
import { recordAudit } from "@/lib/audit";
import { changePasswordSchema, fieldErrors, profileSchema } from "@/lib/validation";
import { actionError, actionSuccess, type ActionState } from "@/lib/action-state";

/**
 * Account settings mutations.
 *
 * Every action re-authorizes the caller and scopes writes to their own row, so
 * a user can never edit or revoke another account's data.
 */

export async function updateProfileAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  let actor;
  try {
    actor = await authorize("STUDENT");
  } catch (error) {
    return actionError(error instanceof Error ? error.message : "Tidak diizinkan.");
  }

  const parsed = profileSchema.safeParse({
    fullName: formData.get("fullName"),
    email: formData.get("email") ?? "",
    phone: formData.get("phone") ?? "",
    school: formData.get("school") ?? "",
    gradeLevel: formData.get("gradeLevel") ?? "",
    bio: formData.get("bio") ?? "",
    avatarUrl: formData.get("avatarUrl") ?? "",
  });

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

  const data = parsed.data;

  if (data.email) {
    const clash = await prisma.user.findFirst({
      where: { email: data.email, NOT: { id: actor.id } },
      select: { id: true },
    });
    if (clash) {
      return actionError("Email sudah digunakan akun lain.", {
        email: "Email sudah terdaftar.",
      });
    }
  }

  await prisma.user.update({
    where: { id: actor.id },
    data: {
      fullName: data.fullName,
      email: data.email || null,
      phone: data.phone || null,
      school: data.school || null,
      gradeLevel: data.gradeLevel || null,
      bio: data.bio || null,
      avatarUrl: data.avatarUrl || null,
    },
  });

  await recordAudit({
    actorId: actor.id,
    action: "PROFILE_UPDATED",
    entity: "User",
    entityId: actor.id,
  });

  revalidatePath("/dashboard/settings");
  revalidatePath("/dashboard");
  return actionSuccess("Profil berhasil diperbarui.");
}

export async function changePasswordAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  let actor;
  try {
    actor = await authorize("STUDENT");
  } catch (error) {
    return actionError(error instanceof Error ? error.message : "Tidak diizinkan.");
  }

  const parsed = changePasswordSchema.safeParse({
    currentPassword: formData.get("currentPassword"),
    newPassword: formData.get("newPassword"),
    confirmPassword: formData.get("confirmPassword"),
  });

  if (!parsed.success) {
    return actionError("Periksa kembali data kata sandi.", fieldErrors(parsed.error));
  }

  const { currentPassword, newPassword } = parsed.data;

  const user = await prisma.user.findUniqueOrThrow({
    where: { id: actor.id },
    select: { passwordHash: true },
  });

  const valid = await verifyPassword(currentPassword, user.passwordHash);
  if (!valid) {
    return actionError("Kata sandi saat ini salah.", {
      currentPassword: "Kata sandi saat ini tidak cocok.",
    });
  }

  if (currentPassword === newPassword) {
    return actionError("Kata sandi baru harus berbeda dari kata sandi saat ini.", {
      newPassword: "Gunakan kata sandi yang berbeda.",
    });
  }

  const passwordHash = await hashPassword(newPassword);
  await prisma.user.update({ where: { id: actor.id }, data: { passwordHash } });

  await recordAudit({
    actorId: actor.id,
    action: "PASSWORD_CHANGED",
    entity: "User",
    entityId: actor.id,
  });

  // Revoke every session — including this one — so a stolen cookie cannot
  // outlive the password change. The user signs in again with the new secret.
  await destroyAllSessionsForUser(actor.id);
  redirect("/login");
}

export async function revokeSessionAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  const sessionId = String(formData.get("sessionId") ?? "");

  try {
    const actor = await authorize("STUDENT");

    const result = await prisma.session.deleteMany({
      where: { id: sessionId, userId: actor.id },
    });
    if (result.count === 0) return actionError("Sesi tidak ditemukan.");

    await recordAudit({
      actorId: actor.id,
      action: "SESSION_REVOKED",
      entity: "Session",
      entityId: sessionId,
    });
  } catch (error) {
    return actionError(error instanceof Error ? error.message : "Tidak diizinkan.");
  }

  revalidatePath("/dashboard/settings");
  return actionSuccess("Sesi berhasil dicabut.");
}

export async function revokeAllSessionsAction(
  _previous: ActionState,
  _formData: FormData
): Promise<ActionState> {
  let actor;
  try {
    actor = await authorize("STUDENT");
  } catch (error) {
    return actionError(error instanceof Error ? error.message : "Tidak diizinkan.");
  }

  await destroyAllSessionsForUser(actor.id);
  await recordAudit({
    actorId: actor.id,
    action: "SESSIONS_REVOKED_ALL",
    entity: "User",
    entityId: actor.id,
  });

  redirect("/login");
}

export async function deleteAccountAction(
  _previous: ActionState,
  formData: FormData
): Promise<ActionState> {
  let actor;
  try {
    actor = await authorize("STUDENT");
  } catch (error) {
    return actionError(error instanceof Error ? error.message : "Tidak diizinkan.");
  }

  if (actor.role === "ADMIN") {
    return actionError(
      "Akun administrator tidak dapat menonaktifkan dirinya sendiri. Minta administrator lain melakukannya."
    );
  }

  const confirmation = String(formData.get("confirmation") ?? "").trim();
  if (confirmation !== actor.username) {
    return actionError("Konfirmasi tidak cocok.", {
      confirmation: `Ketik "${actor.username}" untuk mengonfirmasi.`,
    });
  }

  await prisma.user.update({
    where: { id: actor.id },
    data: { status: "SUSPENDED" },
  });

  await recordAudit({
    actorId: actor.id,
    action: "ACCOUNT_SELF_SUSPENDED",
    entity: "User",
    entityId: actor.id,
  });

  await destroyAllSessionsForUser(actor.id);
  redirect("/login");
}
