'use strict';

const defaultProductosService = require('../../services/productosAdminService');
const {
  validatePriceUpdate,
  validateProductCreate,
  validateProductUpdate,
} = require('./schemas');

function service(deps = {}) {
  return deps.productosService || defaultProductosService;
}

async function updatePrice(command, _config = {}, deps = {}) {
  const payload = validatePriceUpdate(command.payload || {});
  await service(deps).editarProducto(payload.idproducto, { precio1: payload.precio1 });
  return {
    ok: true,
    entity_type: 'product',
    entity_id: payload.idproducto,
    applied: { precio1: payload.precio1 },
  };
}

async function createProduct(command, _config = {}, deps = {}) {
  const payload = validateProductCreate(command.payload || {});
  const result = await service(deps).crearProducto(payload);
  return {
    ok: true,
    entity_type: 'product',
    entity_id: payload.idproducto,
    result,
  };
}

async function updateProduct(command, _config = {}, deps = {}) {
  const payload = validateProductUpdate(command.payload || {});
  const { idproducto, ...changes } = payload;
  const result = await service(deps).editarProducto(idproducto, changes);
  return {
    ok: true,
    entity_type: 'product',
    entity_id: idproducto,
    result,
  };
}

module.exports = { updatePrice, createProduct, updateProduct };
