/**
 * P0-6.5 — enrollment allowlist contract.
 *
 * The middleware redirects every non-allowlisted path to /enroll-2fa
 * when AUTH_2FA_ENFORCED=true and the session user has totpEnabled=false.
 * If the allowlist is wrong, the user gets stuck in a redirect loop
 * (e.g. /settings denied → /enroll-2fa → /settings → ...) so this
 * predicate is load-bearing.
 *
 * Mirror of the production check in src/proxy.ts. Keep them in
 * sync.
 */

const ENROLLMENT_ALLOWLIST = [
    '/enroll-2fa',
    '/settings',
    '/api/user/2fa',
    '/api/auth',
    '/api/notifications',
];

function isEnrollmentAllowlisted(pathname: string): boolean {
    return ENROLLMENT_ALLOWLIST.some((p) => pathname === p || pathname.startsWith(p + '/'));
}

describe('enrollment allowlist (P0-6.5)', () => {
    it('allows the enrollment landing page itself', () => {
        expect(isEnrollmentAllowlisted('/enroll-2fa')).toBe(true);
    });

    it('allows the settings page where 2FA setup lives', () => {
        expect(isEnrollmentAllowlisted('/settings')).toBe(true);
    });

    it('allows nested settings paths (settings/security etc)', () => {
        expect(isEnrollmentAllowlisted('/settings/security')).toBe(true);
        expect(isEnrollmentAllowlisted('/settings/profile')).toBe(true);
    });

    it('allows the 2FA setup/verify API endpoints', () => {
        expect(isEnrollmentAllowlisted('/api/user/2fa')).toBe(true);
        expect(isEnrollmentAllowlisted('/api/user/2fa/verify')).toBe(true);
    });

    it('allows NextAuth endpoints so signout still works', () => {
        expect(isEnrollmentAllowlisted('/api/auth/signout')).toBe(true);
        expect(isEnrollmentAllowlisted('/api/auth/session')).toBe(true);
    });

    it('blocks the main application paths so users cannot bypass enrolment', () => {
        expect(isEnrollmentAllowlisted('/dashboard')).toBe(false);
        expect(isEnrollmentAllowlisted('/monitors')).toBe(false);
        expect(isEnrollmentAllowlisted('/reports')).toBe(false);
        expect(isEnrollmentAllowlisted('/api/monitors')).toBe(false);
    });

    it('does not partial-match prefixes (e.g. /api/auth-something is not /api/auth)', () => {
        expect(isEnrollmentAllowlisted('/api/auth-fake')).toBe(false);
        expect(isEnrollmentAllowlisted('/settings-impostor')).toBe(false);
        expect(isEnrollmentAllowlisted('/enroll-2fa-fake')).toBe(false);
    });
});
