import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { JOBS_FEATURE_ENABLED, JOBS_DISABLED_PUBLIC_FALLBACK } from '@/lib/features';

function jobsDisabledRedirect(request: NextRequest, pathname: string): NextResponse | null {
  if (JOBS_FEATURE_ENABLED) return null;

  // Public job board & posting
  if (
    pathname === '/jobs' ||
    pathname.startsWith('/jobs/') ||
    pathname === '/post-job' ||
    /^\/region\/[^/]+\/jobs(\/|$)/.test(pathname)
  ) {
    return NextResponse.redirect(new URL(JOBS_DISABLED_PUBLIC_FALLBACK, request.url));
  }

  // Customer job portal → browse workers
  if (pathname === '/customer/jobs' || pathname.startsWith('/customer/jobs/')) {
    return NextResponse.redirect(new URL('/workers', request.url));
  }

  // Worker job portal → dashboard
  if (
    pathname === '/worker/jobs' ||
    pathname.startsWith('/worker/jobs/') ||
    pathname === '/worker/applications' ||
    pathname.startsWith('/worker/applications/') ||
    pathname === '/worker/accepted' ||
    pathname.startsWith('/worker/accepted/')
  ) {
    return NextResponse.redirect(new URL('/worker/dashboard', request.url));
  }

  return null;
}

export function middleware(request: NextRequest) {
  const redirected = jobsDisabledRedirect(request, request.nextUrl.pathname);
  if (redirected) return redirected;
  return NextResponse.next();
}

export const config = {
  matcher: [
    '/jobs',
    '/jobs/:path*',
    '/post-job',
    '/region/:slug/jobs',
    '/region/:slug/jobs/:path*',
    '/customer/jobs',
    '/customer/jobs/:path*',
    '/worker/jobs',
    '/worker/jobs/:path*',
    '/worker/applications',
    '/worker/applications/:path*',
    '/worker/accepted',
    '/worker/accepted/:path*',
  ],
};
