import { describe, it, expect } from 'vitest';
import { detectAuthExpiry, type AuthCheckInput } from './browser-session-expiry.js';

const baseProfile = {
  loggedInSelector: 'header.user-menu',
  loginUrlPatterns: ['https://example.com/login**'],
};

describe('detectAuthExpiry', () => {
  it('returns ok when selector found and url not in login patterns', () => {
    const input: AuthCheckInput = {
      profile: baseProfile, finalUrl: 'https://example.com/home',
      statusCode: 200, loggedInSelectorPresent: true,
    };
    expect(detectAuthExpiry(input)).toEqual({ expired: false });
  });

  it('flags login URL match', () => {
    const input: AuthCheckInput = {
      profile: baseProfile, finalUrl: 'https://example.com/login?next=/home',
      statusCode: 200, loggedInSelectorPresent: false,
    };
    expect(detectAuthExpiry(input)).toEqual({ expired: true, reason: 'redirected to login URL' });
  });

  it('flags 401 / 403', () => {
    expect(detectAuthExpiry({
      profile: baseProfile, finalUrl: 'https://example.com/api/me',
      statusCode: 401, loggedInSelectorPresent: false,
    })).toEqual({ expired: true, reason: 'HTTP 401' });
  });

  it('flags missing logged-in selector', () => {
    expect(detectAuthExpiry({
      profile: baseProfile, finalUrl: 'https://example.com/home',
      statusCode: 200, loggedInSelectorPresent: false,
    })).toEqual({ expired: true, reason: 'logged-in selector not found' });
  });

  it('skips selector check when no selector configured', () => {
    expect(detectAuthExpiry({
      profile: { ...baseProfile, loggedInSelector: null }, finalUrl: 'https://example.com/home',
      statusCode: 200, loggedInSelectorPresent: false,
    })).toEqual({ expired: false });
  });
});
