import type { MiddlewareHandler } from 'astro';
import { env } from '@/server/env';

/**
 * Maintenance-mode gate.
 *
 * When MAINTENANCE_MODE=true all requests that are NOT in the allowlist are
 * rewritten to /maintenance (URL preserved in browser address bar).
 *
 * Allowlist: /maintenance, /500, /api/health, /_astro/*, /_image/*,
 *            /icons/*, /brand/*, /sw.js, /manifest.webmanifest, /registerSW.js
 *
 * Must run FIRST in the middleware sequence (before session/DB access) so the
 * gate works even when the database is unavailable.
 */

const ALLOWLIST: Array<string | RegExp> = [
  '/maintenance',
  '/500',
  '/api/health',
  '/sw.js',
  '/manifest.webmanifest',
  '/registerSW.js',
  /^\/_astro\//,
  /^\/_image\//,
  /^\/icons\//,
  /^\/brand\//,
];

function isAllowed(pathname: string): boolean {
  return ALLOWLIST.some((entry) =>
    typeof entry === 'string' ? pathname === entry : entry.test(pathname),
  );
}

export const maintenanceMiddleware: MiddlewareHandler = async (context, next) => {
  if (env.MAINTENANCE_MODE !== 'true') return next();

  const { pathname } = new URL(context.request.url);
  if (isAllowed(pathname)) return next();

  return context.rewrite('/maintenance');
};
