"use server";

import { MediaKind } from "@/lib/db/enums";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect-error";

import { getAdminAppPath, toInternalAdminPath } from "@/lib/admin-routing";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { withFlash } from "@/lib/admin-feedback";
import { countMediaUsageReferences, getMediaAssetById } from "@/lib/media";
import { createStandaloneMediaAsset, deleteMediaAssetAndFile } from "@/lib/media-service";
import { isManagedMediaFilePath } from "@/lib/media-storage";
import { eq } from "drizzle-orm";

import { db } from "@/lib/db";
import { mediaAsset } from "@/lib/db/schema";

async function ensureAdmin() {
  if (!(await isAdminAuthenticated())) {
    await clearAdminSessionCookie();
    redirect(getAdminAppPath("/"));
  }
}


function revalidateMediaPages() {
  revalidatePath(toInternalAdminPath("/"));
  revalidatePath(toInternalAdminPath("/media"));
  revalidatePath(toInternalAdminPath("/portfolio"));
  revalidatePath(toInternalAdminPath("/portfolio/projects"));
}

export async function createMediaAssetAction(formData: FormData) {
  await ensureAdmin();

  try {
    const kindValue = String(formData.get("kind") ?? "IMAGE");
    const kind = kindValue === "DOCUMENT" ? MediaKind.DOCUMENT : MediaKind.IMAGE;

    await createStandaloneMediaAsset({
      kind,
      label: String(formData.get("label") ?? ""),
      uploadFile: formData.get("file"),
    });

    revalidateMediaPages();
    redirect(withFlash(getAdminAppPath("/media"), { success: "Datei gespeichert." }));
  } catch (error) {
    if (isRedirectError(error)) {
      throw error;
    }

    const message = error instanceof Error ? error.message : "Datei konnte nicht gespeichert werden.";
    redirect(withFlash(getAdminAppPath("/media"), { error: message }));
  }
}

export async function deleteMediaAssetAction(formData: FormData) {
  await ensureAdmin();

  const assetId = String(formData.get("assetId") ?? "");

  try {
    const asset = await getMediaAssetById(assetId);

    if (!asset) {
      redirect(withFlash(getAdminAppPath("/media"), { error: "Datei nicht gefunden." }));
    }

    const usageCount = await countMediaUsageReferences(asset.id);

    if (usageCount > 0) {
      redirect(withFlash(getAdminAppPath("/media"), { error: "Datei wird noch verwendet." }));
    }

    await db.delete(mediaAsset).where(eq(mediaAsset.id, asset.id));

    if (isManagedMediaFilePath(asset.url)) {
      await deleteMediaAssetAndFile({
        assetId: asset.id,
        assetUrl: asset.url,
      });
    }

    revalidateMediaPages();
    redirect(withFlash(getAdminAppPath("/media"), { success: "Datei geloescht." }));
  } catch (error) {
    if (isRedirectError(error)) {
      throw error;
    }

    const message = error instanceof Error ? error.message : "Datei konnte nicht geloescht werden.";
    redirect(withFlash(getAdminAppPath("/media"), { error: message }));
  }
}
