import type { AppState, StateRepository } from '@domain/ports/StateRepository';
import type { EventBus } from '@domain/events/EventBus';

export interface DeleteEnclosCommand { type: 'delete-enclos'; enclosId: number; }

export function createDeleteEnclosHandler(state: AppState, repo: StateRepository, events: EventBus) {
  return (cmd: DeleteEnclosCommand): void => {
    const idx = state.enclos.findIndex(e => e.id === cmd.enclosId);
    if (idx < 0) return;
    state.enclos.splice(idx, 1);
    if (state.activeId === cmd.enclosId) {
      state.activeId = state.enclos.length > 0 ? state.enclos[0]!.id : 'dashboard';
    }
    events.emit({ type: 'enclos-deleted', enclosId: cmd.enclosId });
    repo.save(state);
  };
}
