import type { AppState, StateRepository } from '@domain/ports/StateRepository';
import type { GaugeType } from '@domain/value-objects/GaugeType';
import { MAX_GAUGES } from '@domain/entities/Enclos';

export interface ToggleGaugeCommand { type: 'toggle-gauge'; enclosId: number; gaugeId: GaugeType; }
export interface UpdateGaugeLevelCommand { type: 'update-gauge-level'; enclosId: number; gaugeId: GaugeType; level: number; }

export function createToggleGaugeHandler(state: AppState, repo: StateRepository) {
  return (cmd: ToggleGaugeCommand): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc || enc.timer.running) return;
    const i = enc.activeGauges.indexOf(cmd.gaugeId);
    if (i >= 0) {
      enc.activeGauges.splice(i, 1);
    } else {
      // Exclusion mutuelle baffeur/caresseur : même stat, directions opposées
      const SEREN_PAIR: Record<string, GaugeType> = { baffeur: 'caresseur', caresseur: 'baffeur' };
      const opposite = SEREN_PAIR[cmd.gaugeId];
      if (opposite) {
        const oi = enc.activeGauges.indexOf(opposite);
        if (oi >= 0) enc.activeGauges.splice(oi, 1);
      }
      if (enc.activeGauges.length >= MAX_GAUGES) enc.activeGauges.shift();
      enc.activeGauges.push(cmd.gaugeId);
    }
    // Reset timer if gauge changed after a completed session
    if (enc.timer.startTime && !enc.timer.running) {
      enc.timer = { running: false, startTime: null, pausedAt: null, pausedMs: 0, snapGauges: {}, snapStats: {} };
      enc.alerted = {};
    }
    repo.save(state);
  };
}

export function createUpdateGaugeLevelHandler(state: AppState, repo: StateRepository) {
  return (cmd: UpdateGaugeLevelCommand): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc) return;
    enc.gaugeLevels[cmd.gaugeId] = Math.max(0, Math.min(100000, cmd.level));
    repo.save(state);
  };
}
