import { describe, it, expect, vi } from 'vitest';
import type { AppState, StateRepository } from '@domain/ports/StateRepository';
import { EventBus } from '@domain/events/EventBus';
import { createEnclos, addDragodinde } from '@domain/entities/Enclos';
import { createDeleteEnclosHandler } from '@application/commands/DeleteEnclos';
import { createResetStatsHandler } from '@application/commands/ResetStats';

function makeState(): AppState {
  let enc = createEnclos(1);
  enc = addDragodinde(enc);
  return {
    enclos: [enc], activeId: 1, nextEnclosId: 2,
    alarmSound: 'arpege', notifsEnabled: true, ntfyTopic: '',
    archivedStats: [{ baby: 'Dorée et Rousse', couples: 3, babiesObtained: 2 }],
    inventaire: {}, workflows: [],
    accouplements: [{ parentA: 'Rousse', parentB: 'Dorée', baby: 'Dorée et Rousse', gen: 2, couples: 5, babiesObtained: 3, date: '' }],
  };
}

describe('Regression: Stats persistence', () => {
  it('deleting enclos preserves global stats (archivedStats + accouplements)', () => {
    const state = makeState();
    const repo: StateRepository = { load: vi.fn(async () => null), save: vi.fn() };
    const events = new EventBus();
    const handler = createDeleteEnclosHandler(state, repo, events);
    handler({ type: 'delete-enclos', enclosId: 1 });
    // Enclos deleted but stats remain
    expect(state.enclos).toHaveLength(0);
    expect(state.archivedStats).toHaveLength(1);
    expect(state.accouplements).toHaveLength(1);
  });

  it('reset stats clears everything', () => {
    const state = makeState();
    const repo: StateRepository = { load: vi.fn(async () => null), save: vi.fn() };
    createResetStatsHandler(state, repo)({ type: 'reset-stats' });
    expect(state.archivedStats).toHaveLength(0);
    expect(state.accouplements).toHaveLength(0);
  });
});
