"use server";

import { revalidatePath } from "next/cache";
import { prisma } from "@/lib/db";
import { authorize } from "@/lib/auth/rbac";
import { recordAudit } from "@/lib/audit";
import { actionError, actionSuccess, type ActionState } from "@/lib/action-state";

/**
 * Notification mutations.
 *
 * Every statement filters by the authenticated `userId`, so a caller cannot
 * mark or delete another user's notification by guessing an id.
 */

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

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

    const result = await prisma.notification.updateMany({
      where: { id: notificationId, userId: actor.id, readAt: null },
      data: { readAt: new Date() },
    });

    if (result.count === 0) {
      const exists = await prisma.notification.count({
        where: { id: notificationId, userId: actor.id },
      });
      if (exists === 0) return actionError("Notifikasi tidak ditemukan.");
    }
  } catch (error) {
    return actionError(error instanceof Error ? error.message : "Tidak diizinkan.");
  }

  revalidatePath("/dashboard/notifications");
  revalidatePath("/dashboard");
  return actionSuccess("Notifikasi ditandai sudah dibaca.");
}

export async function markAllNotificationsReadAction(
  _previous: ActionState,
  _formData: FormData
): Promise<ActionState> {
  try {
    const actor = await authorize("STUDENT");

    const result = await prisma.notification.updateMany({
      where: { userId: actor.id, readAt: null },
      data: { readAt: new Date() },
    });

    await recordAudit({
      actorId: actor.id,
      action: "NOTIFICATIONS_READ_ALL",
      entity: "Notification",
      metadata: { count: result.count },
    });
  } catch (error) {
    return actionError(error instanceof Error ? error.message : "Tidak diizinkan.");
  }

  revalidatePath("/dashboard/notifications");
  revalidatePath("/dashboard");
  return actionSuccess("Semua notifikasi ditandai sudah dibaca.");
}

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

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

    const result = await prisma.notification.deleteMany({
      where: { id: notificationId, userId: actor.id },
    });

    if (result.count === 0) return actionError("Notifikasi tidak ditemukan.");
  } catch (error) {
    return actionError(error instanceof Error ? error.message : "Tidak diizinkan.");
  }

  revalidatePath("/dashboard/notifications");
  revalidatePath("/dashboard");
  return actionSuccess("Notifikasi dihapus.");
}
