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

const apiMocks = vi.hoisted(() => ({
  dashboardSummary: vi.fn()
}));

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

vi.mock('$lib/api', () => ({
  api: apiMocks
}));

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

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

describe('root route access', () => {
  it('redirects operations users away from the dashboard 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({ fetch: vi.fn() as typeof fetch })).toThrow(
      expect.objectContaining({ status: 307, location: '/mix-calculator' })
    );
  });

  it('loads the dashboard summary for users with dashboard access', () => {
    sessionMocks.hasStoredClientSession.mockReturnValue(true);
    sessionMocks.getStoredClientSession.mockReturnValue({ role: 'internal', permissions: ['view_dashboard'] });
    sessionMocks.hasPermission.mockImplementation((session, key) => session?.permissions?.includes(key) ?? false);
    apiMocks.dashboardSummary.mockResolvedValue({ ok: true });

    const result = load({ fetch: vi.fn() as typeof fetch });

    expect(apiMocks.dashboardSummary).toHaveBeenCalled();
    expect(result).toHaveProperty('summary');
  });
});
