import { productoUsaLotes } from 'src/lotes/usa-lotes';
import { CODIGOS_IMP } from './errores-imp';

export type EfectoLiberacion = 'ENTRA_STOCK' | 'CREA_LOTE' | 'CREA_PRODUCTO' | 'USA_PRODUCTO_EXISTENTE' | 'SIN_INVENTARIO';

export interface ItemLiberacion {
  id: string;
  /** Posición (base 1) en el orden en que la pantalla lista los ítems. */
  linea: number;
  producto: { id: string; codigo: string; descripcion: string } | null;
  chasis: string | null;
  cantidad: number;
  costo_unitario_gs: number;
  maneja_inventario: boolean | null;
  maneja_lote: boolean | null;
  /** AUTOS sin producto asignado: ya hay un producto del catálogo con el chasis como código. */
  producto_existente_por_chasis: boolean;
}

export interface LineaLiberacion {
  linea: number;
  item_id: string;
  producto: { id: string; codigo: string; descripcion: string } | null;
  cantidad: string;
  costo_unitario: string;
  efecto: EfectoLiberacion;
  /** Solo con depósito elegido. */
  pide_lote?: boolean;
}

export interface VistaLiberacion {
  deposito: { id: string; descripcion: string; usa_lotes: boolean } | null;
  lineas: LineaLiberacion[];
  errores: Array<{ codigo: string; linea: number; message: string }>;
}

/**
 * Vista previa de la liberación, pura: la arma `GET /embarques/:id/liberacion` y la valida `liberarEmbarque` (un solo criterio).
 * `pide_lote` (F25) = el depósito usa lotes (`LotesService.depositoUsaLotes`: con sucursal y lotes habilitados en ella) Y
 * `productoUsaLotes` del producto: las dos mitades de `LotesService.usaLotesEnDeposito`. El producto existente por chasis
 * (AUTOS) llega con sus `maneja_*`; sin inventario es `SIN_INVENTARIO` como cualquier otro.
 */
export function armarVistaLiberacion(entrada: {
  perfil: 'AUTOS' | 'CONSUMO_MASIVO' | string;
  items: ItemLiberacion[];
  deposito: { id: string; descripcion: string; usa_lotes: boolean } | null;
}): VistaLiberacion {
  const { perfil, items, deposito } = entrada;
  const lineas: LineaLiberacion[] = [];
  const errores: VistaLiberacion['errores'] = [];

  for (const it of items) {
    const error = (codigo: string, message: string) => errores.push({ codigo, linea: it.linea, message });
    if (!Number.isFinite(it.cantidad) || it.cantidad <= 0) {
      error(CODIGOS_IMP.CANTIDAD_INVALIDA, `Línea ${it.linea}: la cantidad tiene que ser mayor que cero.`);
    }
    if (perfil === 'AUTOS' && !it.chasis?.trim()) {
      error(CODIGOS_IMP.ITEM_SIN_CHASIS, `Línea ${it.linea}: falta el chasis del vehículo.`);
    }
    if (perfil !== 'AUTOS' && !it.producto) {
      error(CODIGOS_IMP.SIN_PRODUCTO_MAPEADO, `Línea ${it.linea}: el ítem no tiene un producto del catálogo asignado.`);
    }

    const sinProducto = !it.producto;
    // El producto que crea la liberación (AUTOS, uno por chasis) maneja inventario y no lote.
    const creaProducto = sinProducto && !it.producto_existente_por_chasis;
    const manejaInventario = creaProducto || it.maneja_inventario === true;
    const pideLote = Boolean(deposito?.usa_lotes) && !creaProducto && productoUsaLotes({ maneja_inventario: manejaInventario, maneja_lote: it.maneja_lote });

    let efecto: EfectoLiberacion;
    if (creaProducto) efecto = 'CREA_PRODUCTO';
    else if (!manejaInventario) efecto = 'SIN_INVENTARIO';
    else if (sinProducto) efecto = 'USA_PRODUCTO_EXISTENTE';
    else efecto = pideLote ? 'CREA_LOTE' : 'ENTRA_STOCK';

    const linea: LineaLiberacion = {
      linea: it.linea,
      item_id: it.id,
      producto: it.producto,
      cantidad: String(it.cantidad),
      costo_unitario: Number(it.costo_unitario_gs ?? 0).toFixed(2),
      efecto,
    };
    if (deposito) linea.pide_lote = pideLote;
    lineas.push(linea);
  }
  return { deposito, lineas, errores };
}
