IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE NAME = 'TRG_EST_PROD_TABLOIDE_CPL_ECOMMERCE')
BEGIN
DROP TRIGGER [dbo].[TRG_EST_PROD_TABLOIDE_CPL_ECOMMERCE]
END
GO

CREATE TRIGGER [dbo].[TRG_EST_PROD_TABLOIDE_CPL_ECOMMERCE] 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 INTEGRADOR_LINX_PROMOCOES (CD_TABLOIDE, CD_FILIAL, DT_INICIO, DS_DESCRICAO, DT_FIM, OPERACAO, CANAL_VENDA)
        SELECT DISTINCT F.CD_TABLOIDE, F.CD_FILIAL, T.DT_INICIO, T.DS_DESCRICAO, T.DT_FIM, 1 AS OPERACAO, T.FLAG_CANAL_VENDA
        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
        WHERE (T.FLAG_DESCONTO_EXCLUSIVO_INTEGRACAO = 1 OR ISNULL(T.FLAG_CANAL_VENDA,0) > 0)
            AND NOT EXISTS (
                SELECT 1
                FROM INTEGRADOR_LINX_PROMOCOES COMM
                WHERE COMM.CD_TABLOIDE = F.CD_TABLOIDE
                  AND COMM.CD_FILIAL = F.CD_FILIAL
                  AND COMM.[STATUS] = 0
            );
    END

    -- Para UPDATE ou DELETE
    IF EXISTS (SELECT 1 FROM DELETED)
    BEGIN
        INSERT INTO INTEGRADOR_LINX_PROMOCOES (CD_TABLOIDE, CD_FILIAL, DT_INICIO, DS_DESCRICAO, DT_FIM, OPERACAO, CANAL_VENDA)
        SELECT DISTINCT F.CD_TABLOIDE, F.CD_FILIAL, T.DT_INICIO, T.DS_DESCRICAO, T.DT_FIM, 1 AS OPERACAO, T.FLAG_CANAL_VENDA
        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
        WHERE (T.FLAG_DESCONTO_EXCLUSIVO_INTEGRACAO = 1 OR ISNULL(T.FLAG_CANAL_VENDA,0) > 0)
            AND NOT EXISTS (
                SELECT 1
                FROM INTEGRADOR_LINX_PROMOCOES COMM
                WHERE COMM.CD_TABLOIDE = F.CD_TABLOIDE
                  AND COMM.CD_FILIAL = F.CD_FILIAL
                  AND COMM.[STATUS] = 0
            );
    END

END 

GO

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


