"""Add products (GEOPROD-5205)

Revision ID: 7a9aa90b6ca3
Revises: d0161bef5b85
Create Date: 2020-11-12 17:05:13.205583

"""
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 = "7a9aa90b6ca3"
down_revision = "d0161bef5b85"
branch_labels = None
depends_on = None

_moscow_tz = pytz.timezone("Europe/Moscow")
products_data = [
    {
        "oracle_id": 511683,
        "title": "Geoservices. Annual program 2. Branded pins on the route",
        "billing_type": "CPM",
        "billing_data": {"base_cpm": "4.2"},
        "platforms": ["NAVI", "MAPS"],
        "campaign_type": "PIN_ON_ROUTE",
        "cpm_filters": [],
    },
    {
        "oracle_id": 511684,
        "title": "Geoservices. Annual program 2. Branded icon in the search menu",
        "billing_type": "FIX",
        "billing_data": {"cost": "12600.00", "time_interval": "WEEKLY"},
        "platforms": ["NAVI"],
        "campaign_type": "CATEGORY_SEARCH_PIN",
        "cpm_filters": [],
    },
]
client_id = 91410815


@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, 'TRY', :billing_type, 0.18, :campaign_type, :platform, 'https://st.yandex-team.ru/GEOPROD-5205', 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
                ),
                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, 1)),
                active_to=_moscow_tz.localize(datetime(2022, 1, 31)),
                billing_data=json.dumps(product_data["billing_data"]),
                cpm_filters=product_data["cpm_filters"],
                client_id=client_id,
            )


@data_migration
def downgrade():
    pass
