'use strict';

const defaultComprasService = require('../../services/comprasService');
const {
  validateCreatePurchase,
  validateCreatePurchaseOrder,
  validateCancelPurchase,
} = require('./schemas');

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

async function createPurchase(command, _config = {}, deps = {}) {
  const payload = validateCreatePurchase(command.payload || {});
  const user = command.requested_by_username || command.requested_by_email || 'ARKHON';
  const result = await service(deps).crearCompra(payload, user);
  const id = result?.idcompra || result?.folio || payload.foliofactura || command.command_id;
  return {
    ok: true,
    entity_type: 'purchase',
    entity_id: String(id),
    result,
  };
}

async function cancelPurchase(command, _config = {}, deps = {}) {
  const payload = validateCancelPurchase(command.payload || {});
  const user = command.requested_by_username || command.requested_by_email || 'ARKHON';
  const result = await service(deps).cancelarCompra(payload.idcompra, user);
  return {
    ok: true,
    entity_type: 'purchase',
    entity_id: payload.idcompra,
    result,
  };
}

async function createPurchaseOrder(command, _config = {}, deps = {}) {
  const payload = validateCreatePurchaseOrder(command.payload || {});
  const user = command.requested_by_username || command.requested_by_email || 'ARKHON';
  const result = await service(deps).crearOrdenCompra(payload, user);
  return {
    ok: true,
    entity_type: 'purchase_order',
    entity_id: String(result?.idordencompra || payload.purchase_order_id),
    result,
  };
}

module.exports = { createPurchase, createPurchaseOrder, cancelPurchase };
