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

/**
 * GET endpoint to check revalidation configuration status
 * Useful for health checks and debugging
 */
export async function GET() {
  const revalidationSecret = process.env.REVALIDATION_SECRET;
  const isConfigured = !!revalidationSecret;

  return NextResponse.json({
    status: "ok",
    revalidationConfigured: isConfigured,
    timestamp: new Date().toISOString(),
    message: isConfigured
      ? "Revalidation API is configured and ready"
      : "Revalidation secret not configured. Set REVALIDATION_SECRET environment variable.",
  });
}

/**
 * POST endpoint to trigger on-demand cache revalidation
 * Called by Strapi lifecycle hooks when content changes
 */
export async function POST(request: NextRequest) {
  const startTime = Date.now();
  const timestamp = new Date().toISOString();

  try {
    const body = await request.json();
    const { tag, path, secret } = body;

    // Verify the secret token
    const revalidationSecret = process.env.REVALIDATION_SECRET;
    if (!revalidationSecret) {
      console.error(
        `[${timestamp}] Revalidation failed: REVALIDATION_SECRET not configured`
      );
      return NextResponse.json(
        { error: "Revalidation secret not configured" },
        { status: 500 }
      );
    }

    if (secret !== revalidationSecret) {
      console.warn(
        `[${timestamp}] Revalidation failed: Invalid secret token from ${request.headers.get("x-forwarded-for") || request.headers.get("remote-addr") || "unknown"}`
      );
      return NextResponse.json(
        { error: "Invalid secret token" },
        { status: 401 }
      );
    }

    // Revalidate by tag, path, or paths array
    if (tag) {
      revalidateTag(tag, "max");
      // Also revalidate page paths so full-route cache is cleared
      const pathByTag: Record<string, string | string[]> = {
        // Global layout (header/footer); tag revalidate alone may not refresh every RSC shell
        footer: "/",
        header: "/",
        "bespoke-page": "/bespoke",
        "home-page": "/",
        "contact-page": "/contact",
        "designo-page": "/designo",
        "fmd-page": "/fmd",
        "news-page": "/news",
        "story-page": "/the-brand",
        // Property listing + all type listing pages (on-demand when any property changes)
        properties: [
          "/properties",
          "/properties/residential",
          "/properties/commercial",
          "/properties/condominium",
          "/properties/land",
        ],
      };
      const pathOrPaths = pathByTag[tag];
      const pathsToRevalidate = pathOrPaths
        ? Array.isArray(pathOrPaths)
          ? pathOrPaths
          : [pathOrPaths]
        : [];
      for (const p of pathsToRevalidate) {
        revalidatePath(p, "page");
      }
      if (tag === "header" || tag === "footer") {
        revalidatePath("/", "layout");
      }
      const duration = Date.now() - startTime;
      console.log(
        `[${timestamp}] ✅ Revalidated cache tag: "${tag}"${pathsToRevalidate.length ? ` and ${pathsToRevalidate.length} path(s)` : ""} (${duration}ms)`
      );
      return NextResponse.json({
        revalidated: true,
        tag,
        paths: pathsToRevalidate.length ? pathsToRevalidate : undefined,
        timestamp,
        duration: `${duration}ms`,
      });
    }

    if (path) {
      revalidatePath(path, "page");
      const duration = Date.now() - startTime;
      console.log(
        `[${timestamp}] ✅ Revalidated path: "${path}" (${duration}ms)`
      );
      return NextResponse.json({
        revalidated: true,
        path,
        timestamp,
        duration: `${duration}ms`,
      });
    }

    const paths = body.paths as string[] | undefined;
    if (Array.isArray(paths) && paths.length > 0) {
      for (const p of paths) {
        if (typeof p === "string" && p) revalidatePath(p, "page");
      }
      const duration = Date.now() - startTime;
      console.log(
        `[${timestamp}] ✅ Revalidated ${paths.length} path(s) (${duration}ms)`
      );
      return NextResponse.json({
        revalidated: true,
        paths,
        timestamp,
        duration: `${duration}ms`,
      });
    }

    console.warn(
      `[${timestamp}] Revalidation failed: Missing tag, path, or paths parameter`
    );
    return NextResponse.json(
      { error: "Missing tag, path, or paths parameter" },
      { status: 400 }
    );
  } catch (error) {
    const duration = Date.now() - startTime;
    const errorMessage = error instanceof Error ? error.message : "Unknown error";
    console.error(
      `[${timestamp}] ❌ Revalidation error (${duration}ms):`,
      errorMessage
    );
    return NextResponse.json(
      {
        error: "Error revalidating cache",
        details: errorMessage,
        timestamp,
      },
      { status: 500 }
    );
  }
}
