IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_EST_PROD_TABLOIDE_CPL_IFOOD')
BEGIN
	DROP TRIGGER TRG_EST_PROD_TABLOIDE_CPL_IFOOD
END
GO

CREATE TRIGGER [dbo].[TRG_EST_PROD_TABLOIDE_CPL_IFOOD] ON [dbo].[EST_PROD_TABLOIDE_CPL]
AFTER INSERT, UPDATE ,DELETE
AS 
BEGIN
  SET NOCOUNT ON;

    -- Para INSERT
    IF EXISTS (SELECT 1 FROM INSERTED) AND NOT EXISTS (SELECT 1 FROM DELETED)
    BEGIN
        INSERT INTO INTEGRA_IFOOD_PROMOCOES (CD_TABLOIDE, CD_FILIAL, OPERACAO)
        SELECT DISTINCT F.CD_TABLOIDE, F.CD_FILIAL, 1 AS OPERACAO
        FROM INSERTED I
        INNER JOIN EST_PROD_TABLOIDE T ON T.CD_TABLOIDE = I.CD_TABLOIDE
        INNER JOIN EST_PROD_TABLOIDE_FILIAL F ON T.CD_TABLOIDE = F.CD_TABLOIDE
        INNER JOIN PRC_FILIAL_CONFIG CFG ON CFG.CD_FILIAL = F.CD_FILIAL
            AND CFG.CD_CHAVE = 'ID_LOJA_IFOOD_MERCHANT'
        WHERE T.FLAG_DESCONTO_EXCLUSIVO_INTEGRACAO = 1
            AND NOT EXISTS (
                SELECT 1
                FROM INTEGRA_IFOOD_PROMOCOES IFOOD
                WHERE IFOOD.CD_TABLOIDE = F.CD_TABLOIDE
                  AND IFOOD.CD_FILIAL = F.CD_FILIAL
                  AND IFOOD.[STATUS] = 0
            );
    END

    -- Para UPDATE ou DELETE
    IF EXISTS (SELECT 1 FROM DELETED)
    BEGIN
        INSERT INTO INTEGRA_IFOOD_PROMOCOES (CD_TABLOIDE, CD_FILIAL, OPERACAO)
        SELECT DISTINCT F.CD_TABLOIDE, F.CD_FILIAL, 2 AS OPERACAO
        FROM (
            SELECT CD_TABLOIDE FROM INSERTED
            UNION
            SELECT CD_TABLOIDE FROM DELETED
        ) I
        INNER JOIN EST_PROD_TABLOIDE T ON T.CD_TABLOIDE = I.CD_TABLOIDE
        INNER JOIN EST_PROD_TABLOIDE_FILIAL F ON T.CD_TABLOIDE = F.CD_TABLOIDE
        INNER JOIN PRC_FILIAL_CONFIG CFG ON CFG.CD_FILIAL = F.CD_FILIAL
            AND CFG.CD_CHAVE = 'ID_LOJA_IFOOD_MERCHANT'
        WHERE T.FLAG_DESCONTO_EXCLUSIVO_INTEGRACAO = 1
            AND NOT EXISTS (
                SELECT 1
                FROM INTEGRA_IFOOD_PROMOCOES IFOOD
                WHERE IFOOD.CD_TABLOIDE = F.CD_TABLOIDE
                  AND IFOOD.CD_FILIAL = F.CD_FILIAL
                  AND IFOOD.[STATUS] = 0
            );
    END

END 

GO
ALTER TABLE [dbo].[EST_PROD_TABLOIDE_CPL] ENABLE TRIGGER [TRG_EST_PROD_TABLOIDE_CPL_IFOOD]
GO



