import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { resolveApiBase } from './lib/api-base';

function getApiBase(): string {
  return resolveApiBase().replace(/\/+$/, '');
}

function getPublicFlagsUrl(): string {
  const base = getApiBase();
  const root = base.endsWith('/api/v1') ? base.slice(0, -'/api/v1'.length) : base;
  return `${root}/api/v1/app/public-flags`;
}

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  if (
    pathname.startsWith('/_next') ||
    pathname.startsWith('/api') ||
    pathname.startsWith('/favicon') ||
    pathname.startsWith('/icon') ||
    pathname.startsWith('/assets') ||
    pathname.startsWith('/maintenance') ||
    pathname.startsWith('/super-admin') ||
    pathname === '/manifest.json' ||
    pathname === '/sw.js' ||
    pathname === '/push-sw.js' ||
    pathname === '/workbox-' ||
    pathname.startsWith('/workbox-') ||
    /\.(png|jpg|jpeg|svg|webp|gif|ico|webmanifest|json|txt|map|woff2?)$/.test(pathname)
  ) {
    return NextResponse.next();
  }

  try {
    const res = await fetch(getPublicFlagsUrl(), { cache: 'no-store' });
    if (res.ok) {
      const data = await res.json();
      if (data?.maintenance_mode) {
        const url = request.nextUrl.clone();
        url.pathname = '/maintenance';
        return NextResponse.redirect(url);
      }
    }
  } catch {
    // If flags endpoint fails, allow normal navigation
  }

  return NextResponse.next();
}

export const config = {
  matcher: '/:path*',
};
