import { NextRequest, NextResponse } from 'next/server';

// Public pages that never require a session
const PUBLIC_PAGES = ['/login', '/setup', '/license-invalid', '/store'];

export async function middleware(request: NextRequest) {
  const sessionCookie = request.cookies.get('staff_track_session');
  const { pathname } = request.nextUrl;

  if (pathname === '/favicon.ico') {
    return NextResponse.rewrite(new URL('/favicon.svg', request.url));
  }

  if (pathname === '/favicon.svg') {
    return NextResponse.next();
  }

  const isPublicPage = PUBLIC_PAGES.some((p) => pathname === p || pathname.startsWith(p + '/'));

  // Always allow API routes used during setup (no session required)
  if (pathname.startsWith('/api/setup/')) {
    return NextResponse.next();
  }

  // Always allow public store API routes (checkout etc.)
  if (pathname.startsWith('/api/store/checkout')) {
    return NextResponse.next();
  }

  if (!sessionCookie && !isPublicPage) {
    // Redirect to /setup instead of /login if setup check is needed;
    // app/page.tsx handles the actual setup detection — here we just send to /login.
    // Setup redirect logic lives in app/page.tsx via isSetupRequired().
    return NextResponse.redirect(new URL('/login', request.url));
  }

  if (sessionCookie && pathname === '/login') {
    return NextResponse.redirect(new URL('/', request.url));
  }

  // If authenticated user tries to access /setup, let app/setup handle it
  // (it will redirect away once setup is complete)

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image).*)'],
};
