'use strict';

const defaultComprasService = require('../../services/comprasService');
const { validateInventoryAdjust, validateInventoryCountApply } = require('./schemas');

function service(deps = {}) {
  return deps.comprasService || defaultComprasService;
}

async function adjust(command, _config = {}, deps = {}) {
  const payload = validateInventoryAdjust(command.payload || {});
  const result = await service(deps).guardarConciliacion([{
    idinsumospresentaciones: payload.idinsumospresentaciones,
    idalmacen: payload.idalmacen,
    conteo_fisico: payload.conteo_fisico,
  }], { usuario: 'ARKHON Cloud', motivo: payload.reason || 'cloud_inventory_adjust' });
  return {
    ok: true,
    entity_type: 'inventory_adjustment',
    entity_id: `${payload.idalmacen}:${payload.idinsumospresentaciones}`,
    result,
  };
}

async function applyCount(command, _config = {}, deps = {}) {
  const payload = validateInventoryCountApply(command.payload || {});
  const inventoryService = service(deps);
  const writer = inventoryService.guardarInventarioFisico || inventoryService.guardarConciliacion;
  const result = await writer.call(
    inventoryService,
    payload.items.map((item) => ({
      idinsumospresentaciones: item.idinsumospresentaciones,
      idalmacen: payload.warehouse_id,
      conteo_fisico: item.counted_qty,
      expected_qty: item.expected_qty,
      unit_cost: item.unit_cost,
    })),
    {
      usuario: command.requested_by_username || command.requested_by_email || 'ARKHON Cloud',
      motivo: payload.reason,
      count_id: payload.count_id,
      command_id: command.command_id,
      idalmacen: payload.warehouse_id,
      effective_at: payload.effective_at,
      capture_policy: payload.capture_policy,
    }
  );
  return {
    ok: true,
    entity_type: 'inventory_count',
    entity_id: payload.count_id,
    warehouse_id: payload.warehouse_id,
    items_total: payload.items.length,
    result,
  };
}

module.exports = { adjust, applyCount };
