import { describe, it, expect, beforeEach } from 'vitest';
import { isPax8Configured, getPax8Client, _resetPax8Client } from './pax8-factory';

beforeEach(() => {
  delete process.env.PAX8_CLIENT_ID;
  delete process.env.PAX8_CLIENT_SECRET;
  _resetPax8Client();
});

describe('isPax8Configured', () => {
  it('returns false when neither env var is set', () => {
    expect(isPax8Configured()).toBe(false);
  });

  it('returns false when only PAX8_CLIENT_ID is set', () => {
    process.env.PAX8_CLIENT_ID = 'id1';
    expect(isPax8Configured()).toBe(false);
  });

  it('returns false when only PAX8_CLIENT_SECRET is set', () => {
    process.env.PAX8_CLIENT_SECRET = 'secret1';
    expect(isPax8Configured()).toBe(false);
  });

  it('returns true when both env vars are set', () => {
    process.env.PAX8_CLIENT_ID = 'id1';
    process.env.PAX8_CLIENT_SECRET = 'secret1';
    expect(isPax8Configured()).toBe(true);
  });
});

describe('getPax8Client', () => {
  it('throws the exact configuration error when not configured', () => {
    expect(() => getPax8Client()).toThrow(
      'PAX8 is not configured — set PAX8_CLIENT_ID and PAX8_CLIENT_SECRET'
    );
  });

  it('returns a client instance when both env vars are set', () => {
    process.env.PAX8_CLIENT_ID = 'id1';
    process.env.PAX8_CLIENT_SECRET = 'secret1';
    expect(getPax8Client()).toBeDefined();
  });

  it('returns the same cached instance on repeated calls', () => {
    process.env.PAX8_CLIENT_ID = 'id1';
    process.env.PAX8_CLIENT_SECRET = 'secret1';
    const first = getPax8Client();
    const second = getPax8Client();
    expect(second).toBe(first);
  });

  it('rebuilds a new instance after _resetPax8Client()', () => {
    process.env.PAX8_CLIENT_ID = 'id1';
    process.env.PAX8_CLIENT_SECRET = 'secret1';
    const first = getPax8Client();
    _resetPax8Client();
    const second = getPax8Client();
    expect(second).not.toBe(first);
  });
});
