import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { isRoute53Configured, getRoute53Client, resetRoute53Client } from './route53-factory';

const ORIGINAL_ENV = { ...process.env };

beforeEach(() => {
  delete process.env.AWS_ACCESS_KEY_ID;
  delete process.env.AWS_SECRET_ACCESS_KEY;
  delete process.env.AWS_REGION;
  resetRoute53Client();
});

afterEach(() => {
  process.env = { ...ORIGINAL_ENV };
  resetRoute53Client();
});

describe('isRoute53Configured', () => {
  it('returns false when AWS_ACCESS_KEY_ID is unset', () => {
    process.env.AWS_SECRET_ACCESS_KEY = 'secret1';
    expect(isRoute53Configured()).toBe(false);
  });

  it('returns false when AWS_SECRET_ACCESS_KEY is unset', () => {
    process.env.AWS_ACCESS_KEY_ID = 'id1';
    expect(isRoute53Configured()).toBe(false);
  });

  it('returns false when both are set to empty strings', () => {
    process.env.AWS_ACCESS_KEY_ID = '';
    process.env.AWS_SECRET_ACCESS_KEY = '';
    expect(isRoute53Configured()).toBe(false);
  });

  it('returns true when both are set to non-empty values', () => {
    process.env.AWS_ACCESS_KEY_ID = 'id1';
    process.env.AWS_SECRET_ACCESS_KEY = 'secret1';
    expect(isRoute53Configured()).toBe(true);
  });
});

describe('getRoute53Client', () => {
  it('throws an Error mentioning AWS_ACCESS_KEY_ID when credentials are absent', () => {
    expect(() => getRoute53Client()).toThrow(/AWS_ACCESS_KEY_ID/);
  });

  it('returns the same cached instance on a second call', () => {
    process.env.AWS_ACCESS_KEY_ID = 'id1';
    process.env.AWS_SECRET_ACCESS_KEY = 'secret1';
    const first = getRoute53Client();
    const second = getRoute53Client();
    expect(second).toBe(first);
  });

  it('returns a different instance after resetRoute53Client()', () => {
    process.env.AWS_ACCESS_KEY_ID = 'id1';
    process.env.AWS_SECRET_ACCESS_KEY = 'secret1';
    const first = getRoute53Client();
    resetRoute53Client();
    const second = getRoute53Client();
    expect(second).not.toBe(first);
  });
});
