"use server";

import { revalidatePath } from "next/cache";
import { hasPermission } from "@/lib/adminAuth";
import { connectDB } from "@/lib/db";
import { Settings } from "@/models/Settings";
import { saveSeoImage, deletePublicUploadImage } from "@/lib/uploads";
import { logAdminActivity } from "@/lib/teamActivity";

type FormState = { error?: string; success?: boolean };

export async function updateSeoSettingsAction(_prev: FormState, formData: FormData): Promise<FormState> {
  if (!(await hasPermission("seo"))) return { error: "Keine Berechtigung." };
  await connectDB();

  const existing = await Settings.findOne({ key: "main" }).select("seoSettings").lean();
  const previousOgImage = existing?.seoSettings?.ogImage || "";
  let ogImage = previousOgImage;
  const previousIndexable = existing?.seoSettings?.indexable !== false;
  const nextIndexable = formData.get("indexable") === "on";

  const file = formData.get("ogImage");
  if (file instanceof File && file.size > 0) {
    try {
      ogImage = await saveSeoImage(file);
    } catch (err) {
      return { error: err instanceof Error ? err.message : "Upload fehlgeschlagen." };
    }
  }
  if (formData.get("removeOgImage") === "on") ogImage = "";
  // Bei Ersetzen oder explizitem Entfernen die alte Datei aufräumen — jeder
  // Upload bekommt einen neuen zufälligen Dateinamen statt das alte Bild zu
  // überschreiben (siehe lib/uploads.ts saveSeoImage).
  if (previousOgImage && previousOgImage !== ogImage) await deletePublicUploadImage(previousOgImage);

  await Settings.findOneAndUpdate(
    { key: "main" },
    {
      $set: {
        seoSettings: {
          defaultMetaDescription: String(formData.get("defaultMetaDescription") || "").trim(),
          defaultMetaDescriptionEn: String(formData.get("defaultMetaDescriptionEn") || "").trim(),
          keywords: String(formData.get("keywords") || "").trim(),
          keywordsEn: String(formData.get("keywordsEn") || "").trim(),
          ogImage,
          googleSiteVerification: String(formData.get("googleSiteVerification") || "").trim(),
          bingSiteVerification: String(formData.get("bingSiteVerification") || "").trim(),
          googleAnalyticsId: String(formData.get("googleAnalyticsId") || "").trim(),
          businessPhone: String(formData.get("businessPhone") || "").trim(),
          priceRange: String(formData.get("priceRange") || "").trim(),
          openingHours: String(formData.get("openingHours") || "").trim(),
          indexable: nextIndexable,
        },
      },
    },
    { upsert: true }
  );
  if (previousIndexable !== nextIndexable) {
    await logAdminActivity(
      "Suchmaschinen-Indexierung geändert",
      nextIndexable ? "Wieder indexierbar" : "Von Suchmaschinen ausgeschlossen"
    );
  }

  revalidatePath("/de/admin/seo");
  revalidatePath("/de");
  revalidatePath("/en");
  revalidatePath("/de/portfolio");
  revalidatePath("/en/portfolio");
  return { success: true };
}
