DROP PROCEDURE IF EXISTS mocha_get_attribute_value;

CREATE PROCEDURE mocha_get_attribute_value
(
    IN p_source_inst_id INT,
    IN p_attribute_inst_id INT,
    IN p_effective_date DATETIME
)
BEGIN
    DECLARE p_tenant_id INT;
    DECLARE z_effective_date DATETIME;

    SET p_tenant_id = mocha_get_current_tenant();

    IF p_effective_date IS NULL THEN
        SET z_effective_date = NOW();
    ELSE
        SET z_effective_date = p_effective_date;
    END IF;

    SELECT att_value FROM mocha_attributes
    WHERE tenant_id = p_tenant_id
    AND src_inst_id = p_source_inst_id
    AND att_inst_id = p_attribute_inst_id
    AND att_effective_date <= z_effective_date
    ORDER BY att_effective_date DESC, id DESC
    LIMIT 1;

END;
