export interface AjusteCalculado {
  fechaAjuste: string;
  mesIndiceInicio: string;
  mesIndiceFin: string;
  indiceInicio: number;
  indiceFin: number;
  coeficiente: number;
  variacionPct: number;
  montoAnterior: number;
  montoNuevo: number;
}

export interface CalendarioEntry {
  fechaAjuste: string;
  mesIndiceInicio: string;
  mesIndiceFin: string;
}

export function calcularAjustesIpc(
  ipcData: Record<string, number>,
  calendario: CalendarioEntry[],
  montoBase: number
): AjusteCalculado[] {
  const ajustes: AjusteCalculado[] = [];
  let montoActual = montoBase;

  for (const cal of calendario) {
    const indiceInicio = ipcData[cal.mesIndiceInicio];
    const indiceFin = ipcData[cal.mesIndiceFin];
    if (!indiceInicio || !indiceFin) break;

    const coeficiente = indiceFin / indiceInicio;
    const montoNuevo = Math.round(montoActual * coeficiente);

    ajustes.push({
      fechaAjuste: cal.fechaAjuste,
      mesIndiceInicio: cal.mesIndiceInicio,
      mesIndiceFin: cal.mesIndiceFin,
      indiceInicio,
      indiceFin,
      coeficiente,
      variacionPct: (coeficiente - 1) * 100,
      montoAnterior: montoActual,
      montoNuevo,
    });

    montoActual = montoNuevo;
  }

  return ajustes;
}

export function obtenerAlquilerEsperado(
  periodo: string,
  ajustes: AjusteCalculado[],
  montoBase: number
): number {
  let monto = montoBase;
  for (const ajuste of ajustes) {
    if (ajuste.fechaAjuste <= periodo) {
      monto = ajuste.montoNuevo;
    } else {
      break;
    }
  }
  return monto;
}

export function generarPeriodos(hastaIncluido: string, fechaInicio: string): string[] {
  const periodos: string[] = [];
  const [anioFin, mesFin] = hastaIncluido.split("-").map(Number);
  let [anio, mes] = fechaInicio.split("-").map(Number);
  while (anio < anioFin || (anio === anioFin && mes <= mesFin)) {
    periodos.push(`${anio}-${String(mes).padStart(2, "0")}`);
    mes++;
    if (mes > 12) { mes = 1; anio++; }
  }
  return periodos;
}
