-- Make fn_get_location tolerate duplicate active rows and clean existing duplicates.
-- Applied on one_lab.

DROP FUNCTION IF EXISTS fn_get_location;
DELIMITER $$
CREATE FUNCTION fn_get_location(PT_SampleStationID INT, PT_OrderHeaderID INT) RETURNS INT
    READS SQL DATA
BEGIN
    DECLARE RTN INT DEFAULT 0;

    SELECT T_OrderLocationM_LocationID INTO RTN
    FROM t_order_location
    WHERE T_OrderLocationT_OrderHeaderID = PT_OrderHeaderID
      AND T_OrderLocationT_SampleStationID = PT_SampleStationID
      AND T_OrderLocationIsActive = 'Y'
    ORDER BY T_OrderLocationID DESC
    LIMIT 1;

    IF RTN = 0 THEN
        SELECT M_LocationID INTO RTN
        FROM m_location
        WHERE M_LocationIsActive = 'Y'
          AND M_LocationT_SampleStationID = PT_SampleStationID
          AND M_LocationPriority = (
              SELECT MAX(M_LocationPriority)
              FROM m_location
              WHERE M_LocationT_SampleStationID = PT_SampleStationID
                AND M_LocationIsActive = 'Y'
          )
        LIMIT 1;
    END IF;

    RETURN RTN;
END$$
DELIMITER ;

-- Cleanup duplicate active rows so each order + sample station keeps only the newest active row.
UPDATE t_order_location current_row
JOIN t_order_location newest_row
  ON newest_row.T_OrderLocationT_OrderHeaderID = current_row.T_OrderLocationT_OrderHeaderID
 AND newest_row.T_OrderLocationT_SampleStationID = current_row.T_OrderLocationT_SampleStationID
 AND newest_row.T_OrderLocationIsActive = 'Y'
 AND newest_row.T_OrderLocationID > current_row.T_OrderLocationID
SET current_row.T_OrderLocationIsActive = 'N',
    current_row.T_OrderLocationLastUpdated = NOW()
WHERE current_row.T_OrderLocationIsActive = 'Y';
