"""GEOPROD-5081 / Убрать наценку за аудиоролик в баннере в Навигаторе

Revision ID: b25360ee36af
Revises: e1932b45ccc9
Create Date: 2020-10-22 16:29:26.496768

"""
from alembic import op

# revision identifiers, used by Alembic.
revision = "b25360ee36af"
down_revision = "e1932b45ccc9"
branch_labels = None
depends_on = None


def upgrade():
    op.execute(
        """
WITH product_rules AS (
    SELECT product_rules_versions.*
      FROM product_rules_versions
     INNER JOIN (
        SELECT product_id, max(version) AS version
        FROM product_rules_versions
        WHERE product_id IN (
            SELECT id FROM products WHERE campaign_type = 'ZERO_SPEED_BANNER'
        )
        GROUP BY product_id
     ) AS product_rules_versions_subq
           ON product_rules_versions_subq.product_id = product_rules_versions.product_id
          AND product_rules_versions_subq.version = product_rules_versions.version
    WHERE '2020-10-22 16:00:00+03:00' <= coalesce(product_rules_versions.active_to, now())
      AND '2020-10-22 16:00:00+03:00' > active_from
),
updating AS (
    UPDATE product_rules_versions
       SET active_to = '2020-10-22 16:00:00+03:00'
      FROM product_rules
     WHERE product_rules.id = product_rules_versions.id
)

INSERT INTO product_rules_versions(product_id, version, active_from, active_to, billing_data, min_budget, cpm_filters)
    SELECT product_id,
           version + 1 AS version,
           '2020-10-22 16:00:00+03:00' AS active_from,
           active_to,
           billing_data,
           min_budget,
           array_remove(cpm_filters, 'creative_presence_audio_banner') AS cpm_filters
    FROM product_rules
        """  # noqa: E501
    )


def downgrade():
    pass
