import { auth } from '@/auth';
import { NextResponse } from 'next/server';

const protectedApiPrefixes = [
  '/api/products',
  '/api/organizations',
  '/api/users',
  '/api/employees',
  '/api/courses',
  '/api/training-records',
  '/api/training-matrix',
  '/api/reports',
  '/api/training-policies',
  '/api/import-employees',
  '/api/master-review',
  '/api/audit-logs',
  '/api/notifications',
  '/api/announcements'
];

export const proxy = auth((req) => {
  const isDashboardRoute = req.nextUrl.pathname.startsWith('/dashboard');
  const isProtectedApiRoute = protectedApiPrefixes.some((prefix) =>
    req.nextUrl.pathname.startsWith(prefix)
  );

  if (!req.auth?.user && (isDashboardRoute || isProtectedApiRoute)) {
    if (isProtectedApiRoute) {
      return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
    }

    const signInUrl = new URL('/auth/sign-in', req.nextUrl.origin);
    signInUrl.searchParams.set('callbackUrl', req.nextUrl.pathname);
    return NextResponse.redirect(signInUrl);
  }

  return NextResponse.next();
});

export const config = {
  matcher: [
    '/((?!api/auth|_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    '/api/products/:path*',
    '/api/organizations/:path*',
    '/api/users/:path*',
    '/api/employees/:path*',
    '/api/courses/:path*',
    '/api/training-records/:path*',
    '/api/training-matrix/:path*',
    '/api/reports/:path*',
    '/api/training-policies/:path*',
    '/api/import-employees/:path*',
    '/api/master-review/:path*',
    '/api/audit-logs/:path*',
    '/api/notifications/:path*',
    '/api/announcements/:path*'
  ]
};
