import { describe, expect, it, vi } from 'vitest';

const sessionMocks = vi.hoisted(() => ({
  getStoredClientSession: vi.fn(),
  hasStoredClientSession: vi.fn(),
  hasModuleAccess: vi.fn(),
  hasPermission: vi.fn()
}));

vi.mock('$lib/session', () => sessionMocks);

import { load } from './+page';

describe('settings route access', () => {
  it('allows users with settings access', () => {
    sessionMocks.hasStoredClientSession.mockReturnValue(true);
    sessionMocks.getStoredClientSession.mockReturnValue({ role: 'internal', permissions: ['view_settings'] });
    sessionMocks.hasPermission.mockImplementation((session, key) => session?.permissions?.includes(key) ?? false);

    expect(load()).toEqual({});
  });

  it('redirects users without settings access to their allowed home route', () => {
    sessionMocks.hasStoredClientSession.mockReturnValue(true);
    sessionMocks.getStoredClientSession.mockReturnValue({
      role: 'internal',
      role_name: 'Operations',
      permissions: ['view_mix_calculator']
    });
    sessionMocks.hasPermission.mockImplementation((session, key) => session?.permissions?.includes(key) ?? false);
    sessionMocks.hasModuleAccess.mockReturnValue(false);

    expect(() => load()).toThrow(expect.objectContaining({ status: 307, location: '/mix-calculator' }));
  });
});
