"""Геосервисы. Годовая программа 23. Рекомендация маршрута

Revision ID: f3b716748a3b
Revises: d0161bef5b85
Create Date: 2020-11-18 13:44:10.115962

"""
import json
import logging
from datetime import datetime

import pytz
import sqlalchemy as sa
from alembic import op

from maps_adv.billing_proxy.lib.db.migration_helpers import data_migration

# revision identifiers, used by Alembic.
revision = "f3b716748a3b"
down_revision = "7a9aa90b6ca3"
branch_labels = None
depends_on = None

_moscow_tz = pytz.timezone("Europe/Moscow")
products_data = [
    {
        "oracle_id": 511652,
        "title": "Геосервисы. Годовая программа 23. Рекомендация маршрута",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "70"},
        "platforms": ["NAVI"],
        "campaign_type": "VIA_POINTS",
        "cpm_filters": [],
    }
]
client_id = 58016825


@data_migration
def upgrade():
    con = op.get_bind()

    cursor = con.execute(
        sa.text(
            """
            SELECT EXISTS (
                SELECT
                FROM clients
                WHERE id = :client_id
            )
        """
        ),
        client_id=client_id,
    )
    client_exists = cursor.scalar()
    if not client_exists:
        logging.getLogger("alembic.runtime.migration").warning(
            "Client for products not found, skipping revision."
        )
        return

    product_oracle_ids = set(
        product_data["oracle_id"] for product_data in products_data
    )
    cursor = con.execute(
        sa.text(
            """
            SELECT EXISTS (
                SELECT
                FROM products
                WHERE oracle_id IN :oracle_ids
            )
        """
        ),
        oracle_ids=tuple(product_oracle_ids),
    )
    any_product_exists = cursor.scalar()
    if any_product_exists:
        logging.getLogger("alembic.runtime.migration").warning(
            "Found products with one of oracle_ids mentioned, skipping revision."
        )
        return

    for product_data in products_data:
        for platform in product_data["platforms"]:
            con.execute(
                sa.text(
                    """
                    WITH
                        inserted_product AS (
                            INSERT INTO products (oracle_id, title, act_text, description, currency, billing_type, vat_value, campaign_type, platform, comment, available_for_agencies, available_for_internal, platforms)
                            VALUES (:oracle_id, :title, :act_text, :description, :currency, :billing_type, :vat, :campaign_type, :platform, :comment, TRUE, TRUE, (:platforms)::platformtype[])
                            RETURNING id
                        ),
                        inserted_version AS (
                            INSERT INTO product_rules_versions (product_id, version, active_from, active_to, billing_data, min_budget, cpm_filters)
                            SELECT id, 1, :active_from, :active_to, :billing_data, 0.0, :cpm_filters
                            FROM inserted_product
                        ),
                        insert_client_restriction AS (
                            INSERT INTO product_client_restrictions (product_id, client_id)
                            SELECT id, :client_id
                            FROM inserted_product
                        )
                    SELECT 1
                    """  # noqa: E501
                ),
                comment="https://st.yandex-team.ru/GEOPROD-4384#5fb4cbc4f589b30523efdbd5",  # noqa: E501
                currency="RUB",
                vat=0.2,
                oracle_id=product_data["oracle_id"],
                title=product_data["title"],
                act_text=product_data["title"],
                description="{} {}".format(
                    product_data["oracle_id"], product_data["title"]
                ),
                billing_type=product_data["billing_type"],
                campaign_type=product_data["campaign_type"],
                platform=platform,
                platforms=[platform],
                active_from=_moscow_tz.localize(datetime(2020, 11, 18)),
                active_to=_moscow_tz.localize(datetime(2021, 1, 31, 23, 59, 59)),
                billing_data=json.dumps(product_data["billing_data"]),
                cpm_filters=product_data["cpm_filters"],
                client_id=client_id,
            )


@data_migration
def downgrade():
    pass
