DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `hedera`.`order_checkConfig`(vSelf INT)
BEGIN
/**
 * Comprueba que la configuración del pedido es correcta.
 *
 * @param vSelf Identificador del pedido
 */
	DECLARE vDeliveryMethod VARCHAR(255);
	DECLARE vLanded DATE;
	DECLARE vAgencyMode INT;
	DECLARE vAddress INT;
	DECLARE vIsAvailable BOOL;
	DECLARE vIsActive BOOL;
	DECLARE vClientFk INT;
	DECLARE vConfigured DATETIME;

	CALL order_checkEditable(vSelf);

	-- Obtiene los datos del pedido

	SELECT d.code, o.date_send, o.agency_id, o.address_id, customer_id, configured
		INTO vDeliveryMethod, vLanded, vAgencyMode, vAddress, vClientFk, vConfigured
		FROM `order` o
			JOIN vn.deliveryMethod d ON d.id = o.delivery_method_id
		WHERE o.id = vSelf;

	-- Comprueba que no ha caducado la configuración

	IF vConfigured IS NULL OR vConfigured < TIMESTAMPADD(DAY, -1, util.VN_NOW()) THEN
		CALL util.throw('orderOutdated');
	END IF;

	-- Comprueba que se ha seleccionado una dirección

	IF vDeliveryMethod IN ('AGENCY', 'DELIVERY') AND vAddress IS NULL THEN
		CALL util.throw ('ORDER_EMPTY_ADDRESS');
	END IF;

	-- Comprueba que el cliente esté activo

	SELECT isActive INTO vIsActive
		FROM vn.client
		WHERE id = vClientFk;

	IF NOT vIsActive THEN
		CALL util.throw ('CLIENT_NOT_ACTIVE');
	END IF;

	-- Comprueba que la agencia es correcta

	CALL vn.zone_getAgency(vAddress, vLanded);

	SELECT COUNT(*) > 0 INTO vIsAvailable
		FROM tmp.zoneGetAgency
		WHERE agencyModeFk = vAgencyMode;

	IF NOT vIsAvailable THEN
		CALL util.throw ('ORDER_INVALID_AGENCY');
	END IF;

	DROP TEMPORARY TABLE tmp.zoneGetAgency;
END$$
DELIMITER ;
