import type { AppState, StateRepository } from '@domain/ports/StateRepository';
import type { GaugeType } from '@domain/value-objects/GaugeType';
import { elapsed } from '@domain/services/GaugeCalculator';

export interface RechargeGaugeCommand {
  type: 'recharge-gauge';
  enclosId: number;
  gaugeId: GaugeType;
  level: number;
}

export function createRechargeGaugeHandler(state: AppState, repo: StateRepository) {
  return (cmd: RechargeGaugeCommand): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc || !enc.timer.startTime) return;

    const atSec = elapsed(enc.timer);
    if (!enc.timer.gaugeRecharges[cmd.gaugeId]) enc.timer.gaugeRecharges[cmd.gaugeId] = [];

    // Consolider : si la dernière recharge est à moins de 5s, la remplacer
    // (évite de polluer le tableau lors de la saisie en temps réel)
    const arr = enc.timer.gaugeRecharges[cmd.gaugeId];
    const last = arr.length > 0 ? arr[arr.length - 1] : null;
    if (last && Math.abs(atSec - last.atSec) < 2) {
      last.atSec = atSec;
      last.level = cmd.level;
    } else {
      arr.push({ atSec, level: cmd.level });
    }

    // Mettre à jour gaugeLevels pour l'affichage de l'input
    enc.gaugeLevels[cmd.gaugeId] = cmd.level;
    repo.save(state);
  };
}
