import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

const MAINTENANCE_HTML = `<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Back soon — Iniyaval Return Gifts</title>
<style>
  body { font-family: system-ui, sans-serif; background: #fff1f2; color: #292524; display: flex; min-height: 100vh; align-items: center; justify-content: center; margin: 0; text-align: center; padding: 24px; }
  div { max-width: 420px; }
  h1 { color: #9f1239; font-size: 1.5rem; }
  p { color: #57534e; font-size: 0.95rem; }
</style></head>
<body><div><h1>We'll be back shortly</h1><p>Iniyaval Return Gifts is doing a bit of housekeeping. Please check back soon.</p></div></body></html>`;

export async function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  const storeSettings = await prisma.storeSettings.findFirst();
  if (storeSettings?.maintenanceMode) {
    return new NextResponse(MAINTENANCE_HTML, { status: 503, headers: { "Content-Type": "text/html" } });
  }

  const redirect = await prisma.redirect.findUnique({ where: { fromPath: pathname } });
  if (redirect && redirect.active) {
    const destination = redirect.toPath.startsWith("http") ? redirect.toPath : new URL(redirect.toPath, request.url);
    return NextResponse.redirect(destination, 308);
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    /*
     * Only run on plausible storefront page paths — skip admin, API routes,
     * Next internals, and static/image files, so this stays cheap and never
     * interferes with the admin panel or asset serving. Admin stays reachable
     * during maintenance mode because of this same exclusion.
     */
    "/((?!admin|api|_next|.*\\..*).*)",
  ],
};
