<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd
        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
    <changeSet id="1" author="bhavinrshah">
        <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
        <![CDATA[
            USE art_relations;;

            DROP TRIGGER IF EXISTS `before_insert_release`;;

            CREATE DEFINER = 'theorchard'@'10.10.%' TRIGGER `before_insert_release` BEFORE INSERT ON `releases` 
            FOR EACH ROW before_insert_release_block: BEGIN
                DECLARE vendorId INT DEFAULT NULL;
                DECLARE projectId INT DEFAULT NULL;

                -- Set the vendor id.
                SET vendorId = (SELECT v.vendor_id FROM vendor v INNER JOIN artist_info ai ON ai.vendor_id = v.vendor_id WHERE ai.artist_id = NEW.artist_id);

                -- Execute trigger only when vendor_id is not NULL.
                IF(vendorId IS NULL) THEN
                    LEAVE before_insert_release_block;
                END IF;

                IF (NEW.project_id IS NOT NULL) THEN
                    IF (NEW.vendor_catalog_number IS NULL OR TRIM(NEW.vendor_catalog_number) = '') THEN
                        SET NEW.vendor_catalog_number = (SELECT p.project_code FROM art_relations.project AS p WHERE p.project_id = NEW.project_id);
                    END IF;
                    LEAVE before_insert_release_block;
                END IF;

                -- Set project code as "Vendor Catalog Number" or "UPC"
                -- Check if 'Vendor Catalog Number' is not NULL or blank then projectCode = vendor_catalog_number
                -- else projectCode = upc
                CALL sp_insert_and_get_project(vendorId, NEW.subaccount_id, NEW.vendor_catalog_number, NEW.upc, NEW.release_name, NEW.artist_id, projectId);

                SET NEW.project_id = projectId;

            END before_insert_release_block;
        ]]>
        </sql>
        <rollback>
            <sql dbms="mysql" endDelimiter=";;" splitStatements="true" stripComments="true">
            <![CDATA[
                USE art_relations;;

                DROP TRIGGER IF EXISTS `before_insert_release`;;
            ]]>
            </sql>
        </rollback>
    </changeSet>
</databaseChangeLog>
