import type { AppState, StateRepository } from '@domain/ports/StateRepository';
import { createDragodinde } from '@domain/entities/Dragodinde';

export interface ClearEnclosCommand    { type: 'clear-enclos';    enclosId: number; }
export interface RenameEnclosCommand   { type: 'rename-enclos';   enclosId: number; name: string; }
export interface ResetTimerCommand     { type: 'reset-timer';     enclosId: number; }
export interface NouvelleFourneeCommand { type: 'nouvelle-fournee'; enclosId: number; }

export function createClearEnclosHandler(state: AppState, repo: StateRepository) {
  return (cmd: ClearEnclosCommand): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc) return;
    enc.dragodindes = [];
    enc.nextDdId = 1;
    enc.activeGauges = [];
    enc.gaugeLevels = { baffeur: 0, caresseur: 0, foudroyeur: 0, abreuvoir: 0, dragofesse: 0, mangeoire: 0 };
    enc.timer = { running: false, startTime: null, pausedAt: null, pausedMs: 0, snapGauges: {}, snapStats: {}, gaugeRecharges: {} };
    enc.alerted = {};
    repo.save(state);
  };
}

export function createRenameEnclosHandler(state: AppState, repo: StateRepository) {
  return (cmd: RenameEnclosCommand): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc || !cmd.name.trim()) return;
    enc.name = cmd.name.trim();
    repo.save(state);
  };
}

export function createResetTimerHandler(state: AppState, repo: StateRepository) {
  return (cmd: ResetTimerCommand): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc) return;
    enc.timer = { running: false, startTime: null, pausedAt: null, pausedMs: 0, snapGauges: {}, snapStats: {}, gaugeRecharges: {} };
    enc.alerted = {};
    repo.save(state);
  };
}

export function createNouvelleFourneeHandler(state: AppState, repo: StateRepository) {
  return (cmd: NouvelleFourneeCommand): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc) return;
    // Reset timer et état de session
    enc.timer = { running: false, startTime: null, pausedAt: null, pausedMs: 0, snapGauges: {}, snapStats: {}, gaugeRecharges: {} };
    enc.alerted = {};
    // Remet les niveaux de jauges à 0
    enc.gaugeLevels = { baffeur: 0, caresseur: 0, foudroyeur: 0, abreuvoir: 0, dragofesse: 0, mangeoire: 0 };
    // Vide toutes les DDs et en ajoute une nouvelle avec les stats de base
    enc.dragodindes = [createDragodinde(1)];
    enc.nextDdId = 2;
    repo.save(state);
  };
}
