import type { AppState, StateRepository } from '@domain/ports/StateRepository';
import { createEnclos, addDragodinde, MAX_ENCLOS } from '@domain/entities/Enclos';

export interface CreateEnclosCommand { type: 'create-enclos'; }

export function createCreateEnclosHandler(state: AppState, repo: StateRepository) {
  return (_cmd: CreateEnclosCommand): void => {
    if (state.enclos.length >= MAX_ENCLOS) return;
    // Gap-filling : premier numéro de slot (1..MAX_ENCLOS) absent des noms existants "Enclos N"
    const usedSlots = new Set<number>();
    for (const e of state.enclos) {
      const m = e.name.match(/^Enclos (\d+)$/);
      if (m) usedSlots.add(Number(m[1]));
    }
    let slot = 1;
    while (usedSlots.has(slot)) slot++;
    let enc = createEnclos(state.nextEnclosId, `Enclos ${slot}`);
    enc = addDragodinde(enc); // Always start with 1 DD
    state.enclos.push(enc);
    state.nextEnclosId++;
    state.activeId = enc.id;
    repo.save(state);
  };
}
