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

import { canAccessRoute, canOpenEditor, getDefaultRouteForRole, getWorkspaceRole } from './workspace-access';

describe('workspace access policy', () => {
  const operationsSession = {
    role: 'internal',
    role_name: 'Operations',
    permissions: ['view_mix_calculator', 'use_mix_calculator', 'save_mix_calculator_session'],
    name: 'Ops User',
    email: 'ops@example.com',
    token: 'token'
  };

  const adminSession = {
    role: 'internal',
    role_name: 'Admin',
    permissions: ['view_dashboard', 'view_mix_calculator', 'use_mix_calculator'],
    name: 'Admin User',
    email: 'admin@example.com',
    token: 'token'
  };

  const fullAccessSession = {
    role: 'internal',
    role_name: 'Full Access',
    permissions: ['edit_products', 'edit_mixes'],
    name: 'Full User',
    email: 'full@example.com',
    token: 'token'
  };

  const leanSession = {
    role: 'internal',
    role_name: 'lean',
    permissions: [
      'view_dashboard',
      'edit_products',
      'edit_mixes',
      'edit_scenarios',
      'manage_client_access',
      'view_settings'
    ],
    module_permissions: {
      dashboard: 'view',
      products: 'edit',
      mix_master: 'edit',
      scenarios: 'edit',
      client_access: 'manage'
    },
    name: 'Lean User',
    email: 'lean@example.com',
    token: 'token'
  };

  const ownerSession = {
    role: 'client',
    client_role: 'superadmin',
    module_permissions: {
      products: 'edit',
      mix_master: 'edit',
      client_access: 'manage'
    },
    name: 'Owner User',
    email: 'owner@example.com',
    token: 'token'
  };

  it('classifies operations users and sends them to mix calculator by default', () => {
    expect(getWorkspaceRole(operationsSession)).toBe('operations');
    expect(getDefaultRouteForRole(operationsSession)).toBe('/mix-calculator');
  });

  it('prevents operations users from opening the dashboard route', () => {
    expect(canAccessRoute(operationsSession, '/')).toBe(false);
    expect(canAccessRoute(operationsSession, '/mix-calculator')).toBe(true);
  });

  it('keeps dashboard access for admins', () => {
    expect(getWorkspaceRole(adminSession)).toBe('admin');
    expect(canAccessRoute(adminSession, '/')).toBe(true);
  });

  it('treats lean users as owner-level internal admins', () => {
    expect(getWorkspaceRole(leanSession)).toBe('admin');
    expect(canOpenEditor(leanSession)).toBe(true);
    expect(canAccessRoute(leanSession, '/scenarios')).toBe(true);
    expect(canAccessRoute(leanSession, '/client-access')).toBe(true);
  });

  it('limits editor access to internal admin sessions', () => {
    expect(canOpenEditor(adminSession)).toBe(true);
    expect(canOpenEditor(ownerSession)).toBe(false);
    expect(canOpenEditor(fullAccessSession)).toBe(false);
    expect(canAccessRoute(ownerSession, '/editor')).toBe(false);
    expect(canAccessRoute(fullAccessSession, '/editor')).toBe(false);
  });
});
