"use server";

import { auth } from "@/auth";
import { db } from "@/db/client";
import { corruptFiles } from "@/db/schema";
import { and, eq, inArray } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";

async function requireAdmin() {
  const session = await auth();
  if (!session) redirect("/login");
  if (!session.user.isAdmin) redirect("/");
  return session;
}

// Approving does not delete anything here. It records the human decision; the
// reporting agent picks the row up and performs the removal, because Ampelos
// mounts these tiers read-only on purpose.
export async function approveCorruptFile(formData: FormData) {
  const session = await requireAdmin();
  const id = String(formData.get("id") ?? "");
  if (!id) return;

  await db
    .update(corruptFiles)
    .set({ status: "approved", reviewedBy: session.user.id, reviewedAt: new Date() })
    .where(and(eq(corruptFiles.id, id), inArray(corruptFiles.status, ["pending", "dismissed"])));

  revalidatePath("/admin/corrupt");
}

export async function dismissCorruptFile(formData: FormData) {
  const session = await requireAdmin();
  const id = String(formData.get("id") ?? "");
  if (!id) return;

  // Dismissed rows are not re-flagged by later agent reports, so a file judged
  // fine stays quiet instead of reappearing every run.
  await db
    .update(corruptFiles)
    .set({ status: "dismissed", reviewedBy: session.user.id, reviewedAt: new Date() })
    .where(and(eq(corruptFiles.id, id), inArray(corruptFiles.status, ["pending", "approved", "failed"])));

  revalidatePath("/admin/corrupt");
}

export async function approveAllPending() {
  const session = await requireAdmin();

  // Deliberately scoped to rows that are pending right now. Anything an agent
  // reports after this click still needs its own approval.
  await db
    .update(corruptFiles)
    .set({ status: "approved", reviewedBy: session.user.id, reviewedAt: new Date() })
    .where(eq(corruptFiles.status, "pending"));

  revalidatePath("/admin/corrupt");
}

export async function retryFailedDeletion(formData: FormData) {
  await requireAdmin();
  const id = String(formData.get("id") ?? "");
  if (!id) return;

  await db
    .update(corruptFiles)
    .set({ status: "approved", deleteError: null })
    .where(and(eq(corruptFiles.id, id), eq(corruptFiles.status, "failed")));

  revalidatePath("/admin/corrupt");
}
