DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticketPositionInPath`(vTicketId INT)
	RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_general_ci
	DETERMINISTIC
BEGIN
	
 DECLARE vRestTicketsMaxOrder INT;
 DECLARE vRestTicketsMinOrder INT;
 DECLARE vRestTicketsPacking INT;
 DECLARE vMyProductionOrder INT;
 DECLARE vPosition VARCHAR(10) DEFAULT 'MID';
 DECLARE vMyPath INT;
 DECLARE vMyWarehouse INT;
 DECLARE PACKING_ORDER INT;
 DECLARE vExpeditionsCount INT;
 DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE;

SELECT `order` 
 INTO PACKING_ORDER
  FROM state
  WHERE code = 'PACKING';

SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0)
 INTO vMyPath, vMyWarehouse, vMyProductionOrder
  FROM ticket t
   LEFT JOIN ticketState ts on ts.ticketFk = t.id
  WHERE t.id = vTicketId;

SELECT (a.`name` = 'VN_VALENCIA') 
 INTO vIsValenciaPath
  FROM `route` r
   JOIN agencyMode am on am.id = r.agencyModeFk
   JOIN agency a on a.id = am.agencyFk
  WHERE r.id = vMyPath;

IF vIsValenciaPath THEN -- Rutas Valencia

 SELECT COUNT(*)
  INTO vExpeditionsCount
   FROM expedition e
    JOIN ticket t ON t.id = e.ticketFk
   WHERE t.routeFk = vMyPath;
   
 SELECT MAX(ts.productionOrder), MIN(ts.productionOrder)
  INTO vRestTicketsMaxOrder, vRestTicketsMinOrder
   FROM ticket t
    LEFT JOIN ticketState ts on t.id = ts.ticketFk
   WHERE t.routeFk = vMyPath
    AND t.warehouseFk = vMyWarehouse
    AND t.id != vTicketid;

 SELECT COUNT(*) 
  INTO vRestTicketsPacking
   FROM ticket t
    LEFT JOIN ticketState ts on t.id = ts.ticketFk
   WHERE ts.productionOrder = PACKING_ORDER
    AND t.routeFk = vMyPath
    AND t.warehouseFk = vMyWarehouse
    AND t.id != vTicketid;

  IF  vExpeditionsCount = 1 THEN
    SET vPosition = 'FIRST';
   ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN
    SET vPosition = 'LAST';
   ELSEIF vRestTicketsPacking THEN
    SET vPosition = 'SHARED';
   ELSE
    SET vPosition = 'MID';
  END IF;

ELSE
 SET vPosition = 'MID';

END IF;

RETURN vPosition;

END$$
DELIMITER ;
