"use server";

import { revalidatePath } from "next/cache";
import { prisma } from "@/lib/prisma";
import { requireSuperAdmin } from "@/lib/auth-helpers";
import { settingDefaults } from "@/lib/settings-defaults";
import type { AdminFormState } from "@/app/actions/admin-products";

const moneyKeys = new Set([
  "shipping.freeThreshold",
  "shipping.morocco",
  "shipping.europe",
  "shipping.world",
]);

function groupOf(key: string): string {
  if (key.startsWith("shipping.")) return "shipping";
  if (key.startsWith("seo.")) return "seo";
  if (key.startsWith("contact.") || key.startsWith("footer.") || key.startsWith("social.")) return "contact";
  if (key.startsWith("story.") || key.startsWith("collection.") || key.startsWith("craft.")) return "content";
  return "general";
}

export async function saveSettingsAction(
  _prev: AdminFormState,
  formData: FormData,
): Promise<AdminFormState> {
  await requireSuperAdmin();

  const updates: { key: string; value: string }[] = [];
  for (const [name, raw] of formData.entries()) {
    if (!name.startsWith("setting.")) continue;
    const key = name.slice("setting.".length);
    if (!(key in settingDefaults)) continue;
    if (typeof raw !== "string") continue;
    let value = raw.trim();

    if (moneyKeys.has(key)) {
      const amount = Number.parseFloat(value.replace(",", "."));
      if (!Number.isFinite(amount) || amount < 0) {
        return { status: "error", message: "Les montants de livraison doivent être des nombres positifs." };
      }
      value = String(Math.round(amount * 100));
    }

    if (key === "brand.name" && !value) {
      return { status: "error", message: "Le nom de la maison est obligatoire." };
    }

    updates.push({ key, value });
  }

  if (updates.length === 0) {
    return { status: "error", message: "Aucun réglage à enregistrer." };
  }

  try {
    await prisma.$transaction(
      updates.map((update) =>
        prisma.websiteSetting.upsert({
          where: { key: update.key },
          update: { value: update.value },
          create: { key: update.key, value: update.value, group: groupOf(update.key) },
        }),
      ),
    );

    revalidatePath("/", "layout");
    revalidatePath("/admin/settings");
    return { status: "success", message: "Les réglages du site ont été enregistrés." };
  } catch (error) {
    console.error("[admin/settings] save failed", error);
    return { status: "error", message: "L'enregistrement des réglages a échoué." };
  }
}
