import { revalidatePath, revalidateTag } from "next/cache";
import { NextRequest, NextResponse } from "next/server";
import { env } from "@/lib/env";

export const dynamic = "force-dynamic";

type SanityWebhookBody = {
  _type?: string;
  slug?: string;
  handle?: string;
};

function normalizePathSlug(value: string) {
  const trimmed = value.trim().replace(/^\/+|\/+$/g, "");
  return trimmed;
}

function revalidateCommonStorefrontPaths() {
  revalidatePath("/", "layout");
  revalidatePath("/");
  revalidatePath("/boutique");
  revalidatePath("/recherche");
  revalidatePath("/showroom");
  revalidatePath("/en-savoir-plus");
  revalidatePath("/cgu");
  revalidatePath("/cgv");
}

export async function POST(request: NextRequest) {
  const secretFromUrl = request.nextUrl.searchParams.get("secret") || "";
  const secretFromHeader = request.headers.get("x-sanity-secret") || "";
  const expectedSecret = env.sanityRevalidateSecret.trim();

  if (!expectedSecret || (secretFromUrl !== expectedSecret && secretFromHeader !== expectedSecret)) {
    return NextResponse.json({ ok: false, message: "Unauthorized" }, { status: 401 });
  }

  let body: SanityWebhookBody = {};

  try {
    body = (await request.json()) as SanityWebhookBody;
  } catch {
    body = {};
  }

  revalidateCommonStorefrontPaths();
  revalidateTag("sanity", "max");

  const slug = typeof body.slug === "string" ? normalizePathSlug(body.slug) : "";
  const handle = typeof body.handle === "string" ? normalizePathSlug(body.handle) : "";
  const type = typeof body._type === "string" ? body._type.trim() : "";

  if (type === "product" && handle) {
    revalidatePath(`/produits/${handle}`);
  }

  if (type === "page" && slug) {
    revalidatePath(`/${slug}`);
  }

  return NextResponse.json({
    ok: true,
    revalidated: true,
    type: type || null,
    slug: slug || null,
    handle: handle || null,
  });
}
