import {
  describe,
  it,
  expect
} from 'vitest';
import type { User } from '../../../../shared-kernel';
import {
  SESSION_EXPIRED_ERROR_CODE,
  collectSessionTokenLookupUrls,
  hasValidPersistedSession
} from './auth-session.rules';

describe('auth-session.rules', () => {
  const user = {
    homeSignalServerUrl: 'https://signal.example.com'
  } as Pick<User, 'homeSignalServerUrl'>;

  it('collects home and active server urls without duplicates', () => {
    expect(collectSessionTokenLookupUrls(user, 'https://signal.example.com')).toEqual(['https://signal.example.com']);

    expect(collectSessionTokenLookupUrls(user, 'http://localhost:3001')).toEqual(['http://localhost:3001', 'https://signal.example.com']);
  });

  it('requires a valid token for a known server url', () => {
    const getToken = (url: string) => (url === 'https://signal.example.com' ? 'token-1' : null);

    expect(hasValidPersistedSession(user, 'https://signal.example.com', getToken)).toBe(true);
    expect(hasValidPersistedSession(user, 'http://localhost:3001', getToken)).toBe(true);
  });

  it('rejects persisted users without any valid session token', () => {
    expect(hasValidPersistedSession(user, 'https://signal.example.com', () => null)).toBe(false);
  });

  it('falls back to any stored token when preferred urls are missing', () => {
    expect(
      hasValidPersistedSession(
        {} as Pick<User, 'homeSignalServerUrl'>,
        null,
        () => null,
        () => true
      )
    ).toBe(true);
  });

  it('exports a stable session-expired error code', () => {
    expect(SESSION_EXPIRED_ERROR_CODE).toBe('SESSION_EXPIRED');
  });
});
