"use server";

import { auth } from "@/auth";
import { db } from "@/db/client";
import { classics, externalIds, watchingNowItems } from "@/db/schema";
import { and, eq, isNull } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";

function optionalString(value: FormDataEntryValue | null) {
  return typeof value === "string" && value.trim() ? value.trim() : null;
}

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

export async function addTimelessClassic(formData: FormData) {
  const session = await requireAdmin();
  const mediaItemId = optionalString(formData.get("mediaItemId"));
  const note = optionalString(formData.get("note"));

  if (!mediaItemId) return;

  await db
    .insert(classics)
    .values({ mediaItemId, note, addedBy: session.user.id })
    .onConflictDoUpdate({
      target: classics.mediaItemId,
      set: { note, addedBy: session.user.id, addedAt: new Date() },
    });

  await db
    .update(watchingNowItems)
    .set({ removedAt: new Date() })
    .where(and(eq(watchingNowItems.mediaItemId, mediaItemId), isNull(watchingNowItems.removedAt)));

  revalidatePath("/admin/inventory");
  revalidatePath("/");
}

/**
 * Confirm, or withdraw confirmation, that a title's TMDB link is the right one.
 *
 * Deliberately a person's act. The link was originally derived by matching a
 * folder name against search results, and no automatic pass over those links
 * can settle the question -- believing a machine's second guess is how the
 * first one went unnoticed. Everything that reads the flag (the renamer, most
 * of all) is trusting a human, which is the only reason it is worth trusting.
 */
export async function setTmdbLinkVerified(formData: FormData) {
  const session = await requireAdmin();
  const mediaItemId = optionalString(formData.get("mediaItemId"));
  const verified = formData.get("verified") === "1";

  if (!mediaItemId) return;

  await db
    .update(externalIds)
    .set(
      verified
        ? { verifiedAt: new Date(), verifiedBy: session.user.id }
        : { verifiedAt: null, verifiedBy: null },
    )
    .where(and(eq(externalIds.mediaItemId, mediaItemId), eq(externalIds.source, "tmdb")));

  revalidatePath("/admin/inventory");
}

export async function removeTimelessClassic(formData: FormData) {
  await requireAdmin();
  const mediaItemId = optionalString(formData.get("mediaItemId"));

  if (!mediaItemId) return;

  await db.delete(classics).where(eq(classics.mediaItemId, mediaItemId));

  revalidatePath("/admin/inventory");
  revalidatePath("/");
}
