"use server";

import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { revalidatePath } from "next/cache";
import {
  addPoolValue,
  removePoolValue,
  TAXONOMY_FIELDS,
  type TaxonomyFieldId,
} from "@/lib/taxonomy";

async function requireAdmin() {
  const session = await getServerSession(authOptions);
  if (!session) throw new Error("Non autorizzato");
}

function assertField(fieldId: string): asserts fieldId is TaxonomyFieldId {
  if (!(fieldId in TAXONOMY_FIELDS)) throw new Error(`Tassonomia non valida: ${fieldId}`);
}

function revalidateAll() {
  revalidatePath("/admin/impostazioni");
  revalidatePath("/admin/offers");
  revalidatePath("/admin/catalog");
}

export async function addTaxonomyValue(fieldId: string, value: string): Promise<void> {
  await requireAdmin();
  assertField(fieldId);
  await addPoolValue(fieldId, value);
  revalidateAll();
}

// Global delete: removes the value from the pool AND cascade-strips it from every
// offer/service using it.
export async function removeTaxonomyValue(fieldId: string, value: string): Promise<void> {
  await requireAdmin();
  assertField(fieldId);
  await removePoolValue(fieldId, value);
  revalidateAll();
}
