"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { requirePermission } from "@/lib/permissions";

const BASE = "/iv-manage-84x2/seo";

export async function updateProductSeo(productId: string, formData: FormData) {
  await requirePermission("seo", "edit");
  const metaTitle = String(formData.get("metaTitle") ?? "").trim().slice(0, 70) || null;
  const metaDescription = String(formData.get("metaDescription") ?? "").trim().slice(0, 300) || null;
  const product = await prisma.product.update({ where: { id: productId }, data: { metaTitle, metaDescription } });
  revalidatePath(BASE);
  revalidatePath(`${BASE}/meta-titles`);
  revalidatePath(`${BASE}/meta-descriptions`);
  revalidatePath(`/product/${product.slug}`);
  redirect(`${BASE}?success=Product+SEO+updated.`);
}

export async function updateCategorySeo(categoryId: string, formData: FormData) {
  await requirePermission("seo", "edit");
  const metaTitle = String(formData.get("metaTitle") ?? "").trim().slice(0, 70) || null;
  const metaDescription = String(formData.get("metaDescription") ?? "").trim().slice(0, 300) || null;
  await prisma.category.update({ where: { id: categoryId }, data: { metaTitle, metaDescription } });
  revalidatePath(`${BASE}/categories`);
  revalidatePath(`${BASE}/meta-titles`);
  revalidatePath(`${BASE}/meta-descriptions`);
  revalidatePath("/shop");
  redirect(`${BASE}/categories?success=Category+SEO+updated.`);
}

export async function updatePageSeo(pageId: string, formData: FormData) {
  await requirePermission("seo", "edit");
  const title = String(formData.get("title") ?? "").trim().slice(0, 70) || null;
  const description = String(formData.get("description") ?? "").trim().slice(0, 300) || null;
  const page = await prisma.pageSeo.update({ where: { id: pageId }, data: { title, description } });
  revalidatePath(`${BASE}/pages`);
  revalidatePath(`${BASE}/meta-titles`);
  revalidatePath(`${BASE}/meta-descriptions`);
  revalidatePath(page.path);
  redirect(`${BASE}/pages?success=Page+SEO+updated.`);
}

export async function createRedirect(formData: FormData) {
  await requirePermission("seo", "add");
  let fromPath = String(formData.get("fromPath") ?? "").trim();
  let toPath = String(formData.get("toPath") ?? "").trim();
  if (!fromPath.startsWith("/")) fromPath = `/${fromPath}`;
  if (!toPath.startsWith("/") && !/^https?:\/\//.test(toPath)) toPath = `/${toPath}`;
  fromPath = fromPath.replace(/\/+$/, "") || "/";

  if (!fromPath || !toPath) redirect(`${BASE}/redirects?error=Both+paths+are+required`);
  if (fromPath === toPath) redirect(`${BASE}/redirects?error=From+and+to+can%27t+be+the+same`);

  const existing = await prisma.redirect.findUnique({ where: { fromPath } });
  if (existing) redirect(`${BASE}/redirects?error=A+redirect+from+that+path+already+exists`);

  await prisma.redirect.create({ data: { fromPath, toPath } });
  revalidatePath(`${BASE}/redirects`);
  redirect(`${BASE}/redirects?success=Redirect+created.`);
}

export async function toggleRedirect(id: string) {
  await requirePermission("seo", "edit");
  const r = await prisma.redirect.findUniqueOrThrow({ where: { id } });
  await prisma.redirect.update({ where: { id }, data: { active: !r.active } });
  revalidatePath(`${BASE}/redirects`);
  redirect(`${BASE}/redirects?success=Redirect+updated.`);
}

export async function deleteRedirect(id: string) {
  await requirePermission("seo", "delete");
  await prisma.redirect.delete({ where: { id } });
  revalidatePath(`${BASE}/redirects`);
  redirect(`${BASE}/redirects?success=Redirect+deleted.`);
}
