"""Add products to apply prices for Turkish clients (GEOADVDEV-2648)

Revision ID: c084d6b8252e
Revises: 272cd6fbc846
Create Date: 2020-02-06 17:44:17.492375

"""
import json
import logging
from datetime import datetime, timedelta
from decimal import Decimal

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 = "c084d6b8252e"
down_revision = "272cd6fbc846"
branch_labels = None
depends_on = None

turkey_tz = pytz.timezone("Europe/Moscow")  # same as in Moscow
all_types = ("PIN_ON_ROUTE", "BILLBOARD", "ZERO_SPEED_BANNER")
product_data_by_campaign_type = {
    "PIN_ON_ROUTE": {
        "oracle_id": 509941,
        "title": "Branded Pop-Up Pins",
        "act_text": "Branded Pop-Up Pins",
        "description": "Branded Pop-Up Pins kullanıcının, rotasında devam ederken yakınında bulunan reklam verenin lokasyonunu  markalı pin şeklinde haritada gördüğü reklam modelidir.",  # noqa: E501
    },
    "BILLBOARD": {
        "oracle_id": 509951,
        "title": "Digital Billboards",
        "act_text": "Digital Billboards",
        "description": "Digital billboards; markanın fiziksel lokasyonundan bağımsız olarak hedeflemek istediği bölgelerin harita üzerinde işaretlendiği reklam modelidir.",  # noqa: E501
    },
    "ZERO_SPEED_BANNER": {
        "oracle_id": 509953,
        "title": "Zero Speed Banner",
        "act_text": "Zero Speed Banner",
        "description": "Zero Speed Banner sıfır km anında kullanıcılara iletişiminizi yapabileceğiniz İletişim modelidir. Ekranın alt kısımda otomatik olarak banner belirir. Bannerı yukarı kaydıran kullanıcılar markanın mesajını görür.",  # noqa: E501
    },
}
prices_data = [
    {
        "client_id": 74487715,
        "campaign_types": all_types,
        "cpm": Decimal("6.0"),
        "valid_until": datetime(2020, 12, 31),
    },
    {
        "client_id": 74434965,
        "campaign_types": all_types,
        "cpm": Decimal("3.0"),
        "valid_until": datetime(2021, 1, 1),
    },
    {
        "client_id": 74434533,
        "campaign_types": all_types,
        "cpm": Decimal("4.0"),
        "valid_until": datetime(2020, 12, 31),
    },
    {
        "client_id": 74434988,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 12, 31),
    },
    {
        "client_id": 64292002,
        "campaign_types": ["PIN_ON_ROUTE"],
        "cpm": Decimal("3.0"),
        "valid_until": datetime(2021, 1, 1),
    },
    {
        "client_id": 64292002,
        "campaign_types": ["ZERO_SPEED_BANNER"],
        "cpm": Decimal("10.0"),
        "valid_until": datetime(2021, 1, 1),
    },
    {
        "client_id": 74434951,
        "campaign_types": all_types,
        "cpm": Decimal("3.0"),
        "valid_until": datetime(2021, 1, 1),
    },
    {
        "client_id": 67243592,
        "campaign_types": all_types,
        "cpm": Decimal("3.0"),
        "valid_until": datetime(2021, 1, 1),
    },
    {
        "client_id": 70968581,
        "campaign_types": all_types,
        "cpm": Decimal("6.0"),
        "valid_until": datetime(2021, 1, 13),
    },
    {
        "client_id": 63991057,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 5, 31),
    },
    {
        "client_id": 63958042,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 5, 31),
    },
    {
        "client_id": 67267440,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 5, 31),
    },
    {
        "client_id": 74487693,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 3, 31),
    },
    {
        "client_id": 64295915,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 5, 31),
    },
    {
        "client_id": 74434809,
        "campaign_types": all_types,
        "cpm": Decimal("10.0"),
        "valid_until": datetime(2020, 12, 31),
    },
    {
        "client_id": 64291368,
        "campaign_types": all_types,
        "cpm": Decimal("6.0"),
        "valid_until": datetime(2020, 12, 31),
    },
    {
        "client_id": 74432805,
        "campaign_types": all_types,
        "cpm": Decimal("3.0"),
        "valid_until": datetime(2020, 1, 31),
    },
    {
        "client_id": 67229666,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 9, 25),
    },
    {
        "client_id": 65904958,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 10, 30),
    },
    {
        "client_id": 69959615,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 2, 21),
    },
    {
        "client_id": 74432823,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 3, 1),
    },
    {
        "client_id": 74432833,
        "campaign_types": all_types,
        "cpm": Decimal("5.0"),
        "valid_until": datetime(2020, 4, 1),
    },
]


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

    # Check if all the clients exist, if not - bail out
    client_ids = set(price_data["client_id"] for price_data in prices_data)
    cursor = con.execute(
        sa.text(
            """
            SELECT count(*)
            FROM clients
            WHERE id IN :client_ids
        """
        ),
        client_ids=tuple(client_ids),
    )
    found_clients_count = cursor.scalar()
    if found_clients_count != len(client_ids):
        logging.getLogger("alembic.runtime.migration").warning(
            "Not all clients found, skipping revision."
        )
        return

    for price_data in prices_data:
        for campaign_type in price_data["campaign_types"]:
            product_data = product_data_by_campaign_type[campaign_type]
            active_from = min(
                datetime(2020, 2, 6), price_data["valid_until"] - timedelta(days=1)
            )

            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', 'CPM', 0.18, :campaign_type, 'NAVI', '', TRUE, TRUE, ARRAY['NAVI']::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, ARRAY[]::varchar(128)[]
                            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["act_text"],
                description=product_data["description"],
                campaign_type=campaign_type,
                active_from=active_from,
                active_to=turkey_tz.localize(price_data["valid_until"]).strftime(
                    "%Y-%m-%d %H:%M:%S%z"
                ),
                billing_data=json.dumps({"base_cpm": str(price_data["cpm"])}),
                client_id=price_data["client_id"],
            )


@data_migration
def downgrade():
    # Nothing we can do about it
    pass
