import {
  getEncounterById,
  getEncountersByTier,
  getLibraryVersion,
  getRandomEncounterByTier,
  pickFlavor,
} from './encounter-library';

function seqRng(values: number[]): () => number {
  let i = 0;
  return () => values[i++ % values.length];
}

describe('encounter-library', () => {
  it('getLibraryVersion returns a semver string', () => {
    expect(getLibraryVersion()).toMatch(/^\d+\.\d+\.\d+$/);
  });

  it('getEncounterById returns the correct encounter', () => {
    const enc = getEncounterById('generator_repair');
    expect(enc?.key).toBe('generator_repair');
    expect(enc?.baseProbability).toBeGreaterThan(0);
    expect(enc?.tags).toContain('generator');
  });

  it('getEncounterById returns undefined for unknown key', () => {
    expect(getEncounterById('does_not_exist')).toBeUndefined();
  });

  it('getEncountersByTier returns only encounters of that tier', () => {
    const tier1 = getEncountersByTier(1);
    expect(tier1.every((e) => e.tier === 1)).toBe(true);
    expect(tier1.length).toBeGreaterThan(0);
  });

  it('getRandomEncounterByTier returns an encounter from the tier', () => {
    const rng = seqRng([0, 0.5, 0.99]);
    for (let i = 0; i < 3; i++) {
      const enc = getRandomEncounterByTier(1, rng);
      expect(enc.tier).toBe(1);
    }
  });

  it('pickFlavor returns a success flavor on success', () => {
    const enc = getEncounterById('generator_repair')!;
    const flavor = pickFlavor(enc, { success: true }, seqRng([0]));
    expect(enc.flavorSuccess).toContain(flavor);
  });

  it('pickFlavor returns a failure flavor on failure', () => {
    const enc = getEncounterById('generator_repair')!;
    const flavor = pickFlavor(enc, { success: false }, seqRng([0]));
    expect(enc.flavorFailure).toContain(flavor);
  });

  it('all encounters have non-empty flavor arrays', () => {
    for (const tier of [1, 2, 3] as const) {
      for (const enc of getEncountersByTier(tier)) {
        expect(enc.flavorSuccess.length).toBeGreaterThan(0);
        expect(enc.flavorFailure.length).toBeGreaterThan(0);
      }
    }
  });
});
