import { withAuth } from 'next-auth/middleware';
import { PERMISSIONS } from './utills/constant';
import { NextResponse } from 'next/server';

function matcher(url: string, paths: string[]) {
  if (paths?.includes(url)) {
    return true;
  }

  for (const path of paths) {
    const regex = new RegExp('^' + path.replace(/:[^/]+/g, '([^/]+)') + '$');
    const match = url.match(regex);
    if (match) {
      return true;
    }
  }

  return false;
}

export default withAuth(
  function middleware(req) {
    const token = req?.nextauth?.token as any;
    const userRole = token?.role?.name; // Access the role name from the token
    // Restrict access to these paths only to super_admin role
    const superAdminPaths = ['/dissociation', '/lead-routing', '/lead-routing/add', '/lead-routing/edit/:path*'];
    const cityHeadOrSuperAdminPaths = ['/lead-transfer', '/promotions', '/promotions/history'];

    if (matcher(req.nextUrl.pathname, superAdminPaths) && userRole !== 'super_admin') {
      return NextResponse.redirect(new URL('/permission-denied', req.url));
    }

    if (cityHeadOrSuperAdminPaths.includes(req.nextUrl.pathname) && userRole !== 'city_head' && userRole !== 'super_admin') {
      return NextResponse.redirect(new URL('/permission-denied', req.url));
    }

    // Handle other permissions
    // eslint-disable-next-line spellcheck/spell-checker
    const alwaysAllowedPaths = ['/', '/dashboard', '/profile', '/permission-denied', '/enquiries', '/super-hot-leads', '/dissociation', '/lead-routing', '/lead-routing/add', '/lead-routing/edit/:path*', '/lead-transfer', '/promotions', '/promotions/history', '/onboarding'];
    const collectPath = token
      ? token?.permissions?.reduce(
        (acc: string[], curr: string) => [...acc, ...(PERMISSIONS[curr]?.path || [])],
        alwaysAllowedPaths
      )
      : [];

    const result = matcher(req.nextUrl.pathname, collectPath);
    if (!result) {
      return NextResponse.redirect(new URL('/permission-denied', req.url));
    }
  }
);

export const config = {
  matcher: [
    '/',
    '/dashboard',
    // eslint-disable-next-line spellcheck/spell-checker
    '/onboarding',
    '/profile/components/first-change-password',
    '/employees',
    '/employees/add-employee',
    '/employees/edit-employee',
    '/employees/view-employee',
    '/role',
    '/role/mapping',
    '/profile',
    '/designations',
    '/customer',
    '/cities',
    '/builders',
    '/enquiries',
    '/enquiries/add-lead',
    '/enquiries/view-lead/:path*',
    '/super-hot-leads',
    '/configuration',
    '/lead-requests',
    '/lead-requests/add-leadRequest/:path*',
    '/dissociation',
    '/lead-routing',
    '/lead-routing/add',
    '/lead-routing/edit/:path*',
    '/lead-transfer',
    '/promotions',
    '/promotions/history',
    '/launches',
    '/launches/view-edit-launch/:path*',
    '/launches/add-projects',
    '/launches/edit-project',
    '/launches/view-project',
    '/launches/add-launch',
    '/region',
    '/roles',
    '/roles-mapping',
    '/permission-denied',
  ],
};
