DROP PROCEDURE IF EXISTS mocha_assign_relationship;

CREATE PROCEDURE mocha_assign_relationship
(
    IN p_source_inst_id INT,
    IN p_relationship_inst_id INT,
    IN p_destination_inst_id INT,
    IN p_user_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;


    -- insert record first
    INSERT INTO mocha_relationships
    (tenant_id, source_inst_id, relationship_inst_id, destination_inst_id, user_inst_id, effective_date)
    VALUES
    (p_tenant_id, p_source_inst_id, p_relationship_inst_id, p_destination_inst_id, p_user_inst_id, z_effective_date);

END;
