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

export interface RenameDragodindeCommand  { type: 'rename-dragodinde';        enclosId: number; ddId: number; name: string; }
export interface UpdateDdStatCommand      { type: 'update-dd-stat';           enclosId: number; ddId: number; stat: StatType; value: number; }
export interface UpdateDdSerenTargetCmd   { type: 'update-dd-seren-target';   enclosId: number; ddId: number; target: number | null; }
export interface UpdateDdLevelTargetCmd   { type: 'update-dd-level-target';   enclosId: number; ddId: number; target: number | null; }
export interface ReorderDragodindeCommand { type: 'reorder-dragodinde';       enclosId: number; fromDdId: number; toDdId: number; }

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

export function createUpdateDdStatHandler(state: AppState, repo: StateRepository) {
  return (cmd: UpdateDdStatCommand): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc) return;
    const dd = enc.dragodindes.find(d => d.id === cmd.ddId);
    if (!dd) return;
    dd.stats[cmd.stat] = cmd.value;
    repo.save(state);
  };
}

export function createUpdateDdSerenTargetHandler(state: AppState, repo: StateRepository) {
  return (cmd: UpdateDdSerenTargetCmd): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc) return;
    const dd = enc.dragodindes.find(d => d.id === cmd.ddId);
    if (!dd) return;
    dd.sereniteTarget = cmd.target;
    repo.save(state);
  };
}

export function createUpdateDdLevelTargetHandler(state: AppState, repo: StateRepository) {
  return (cmd: UpdateDdLevelTargetCmd): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc) return;
    const dd = enc.dragodindes.find(d => d.id === cmd.ddId);
    if (!dd) return;
    dd.levelTarget = cmd.target;
    repo.save(state);
  };
}

export function createReorderDragodindeHandler(state: AppState, repo: StateRepository) {
  return (cmd: ReorderDragodindeCommand): void => {
    const enc = state.enclos.find(e => e.id === cmd.enclosId);
    if (!enc) return;
    const fromIdx = enc.dragodindes.findIndex(d => d.id === cmd.fromDdId);
    const toIdx   = enc.dragodindes.findIndex(d => d.id === cmd.toDdId);
    if (fromIdx < 0 || toIdx < 0) return;
    const [item] = enc.dragodindes.splice(fromIdx, 1);
    enc.dragodindes.splice(toIdx, 0, item!);
    repo.save(state);
  };
}
