import { revalidateTag } from "next/cache";
import { NextRequest, NextResponse } from "next/server";

const DEFAULT_TAGS = {
  wp: ["wp"],
  prestashop: ["ps-wp"],
  all: ["wp", "ps-wp"],
} as const;

type SiteKey = keyof typeof DEFAULT_TAGS;

type RevalidatePayload = {
  site?: SiteKey;
  tags?: string[];
  tag?: string;
  includeBaseTags?: boolean;
};

const getBearerToken = (request: NextRequest) => {
  const authHeader = request.headers.get("authorization") || "";
  if (authHeader.startsWith("Bearer ")) {
    return authHeader.slice("Bearer ".length).trim();
  }
  return null;
};

export async function POST(request: NextRequest) {
  const secret = process.env.REVALIDATE_WEBHOOK_SECRET;

  if (!secret) {
    return NextResponse.json(
      { ok: false, error: "REVALIDATE_WEBHOOK_SECRET is not configured" },
      { status: 500 }
    );
  }

  const token = getBearerToken(request);
  if (token !== secret) {
    return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
  }

  let payload: RevalidatePayload = {};

  try {
    payload = (await request.json()) as RevalidatePayload;
  } catch {
    payload = {};
  }

  const site = payload.site || "all";
  const baseTags = DEFAULT_TAGS[site] || DEFAULT_TAGS.all;
  const customTags = [...(payload.tags || []), ...(payload.tag ? [payload.tag] : [])].filter(Boolean);
  const shouldIncludeBaseTags = payload.includeBaseTags ?? customTags.length === 0;
  const tagsToRevalidate = Array.from(
    new Set(shouldIncludeBaseTags ? [...baseTags, ...customTags] : customTags)
  );

  if (tagsToRevalidate.length === 0) {
    return NextResponse.json(
      { ok: false, error: "No tags provided to revalidate" },
      { status: 400 }
    );
  }

  tagsToRevalidate.forEach((tag) => revalidateTag(tag));

  return NextResponse.json({
    ok: true,
    revalidated: tagsToRevalidate,
    at: new Date().toISOString(),
  });
}
