# flake8: noqa
fetch_biz_state_by_biz_id = """
    SELECT
        biz_id,
        slug,
        permalink,
        stable_version,
        unstable_version,
        published,
        blocked
    FROM biz_state
    WHERE biz_id = $1
"""

fetch_biz_state_by_slug = """
    with found_aliases AS (
        select biz_id from slug_aliases where slug = $1 and expiration_date > now() limit 1
    )
    SELECT
        bs.biz_id as biz_id,
        $1 as slug,
        bs.permalink as permalink,
        bs.stable_version as stable_version,
        bs.unstable_version as unstable_version,
        bs.published as published,
        bs.blocked as blocked
    FROM biz_state as bs
    WHERE bs.slug = $1 or bs.biz_id = (select biz_id from found_aliases);
"""

create_biz_state = """
    INSERT INTO biz_state (biz_id, slug, permalink)
    VALUES ($1, $2, $3)
"""

check_slug_is_in_use = """
    select exists(
        select 1 from(
            select slug, biz_id
            from slug_aliases
            where expiration_date > now()
            union all
            select slug, biz_id
            from biz_state
        ) as tmp
        where slug = $1
        and biz_id != $2
          limit 1
    )
"""

update_biz_state_slug = """
    WITH before AS (
        INSERT INTO slug_aliases(biz_id, slug)
        SELECT biz_id, slug FROM biz_state WHERE biz_id = $1
        RETURNING *
    )
    UPDATE biz_state
    SET slug = $2
    WHERE biz_id = $1
    RETURNING TRUE
"""

alias_for_slug = """
    SELECT * 
    FROM slug_aliases 
    WHERE slug = $1 AND biz_id <> $2 AND expiration_date > now()
"""

aliases_cnt = """
    SELECT count(*) as cnt
    FROM slug_aliases
    WHERE biz_id = $1 AND expiration_date > now()
"""

update_biz_state_permalink = """
    UPDATE biz_state
    SET permalink = $2
    WHERE biz_id = $1
    RETURNING TRUE
"""

update_biz_state_set_blocked = """
    UPDATE biz_state
    SET blocked = $2, blocking_data = $3
    WHERE biz_id = $1
    RETURNING TRUE
"""

update_permalink_from_geosearch = """
    UPDATE biz_state
    SET permalink = $2
    WHERE permalink = $1
    RETURNING TRUE
"""

fetch_published_slugs = """
    SELECT slug
    FROM biz_state
    WHERE published
    ORDER BY biz_id
    LIMIT $2 OFFSET $1
"""

set_landing_data = """
    WITH
    biz_state_matched AS (
        SELECT
            (
                CASE
                    WHEN $2 = 'STABLE' THEN stable_version
                    WHEN $2 = 'UNSTABLE' THEN unstable_version
                END
            ) AS current_version
        FROM biz_state
        WHERE biz_id = $1
    ),
    deleted_landing_data AS (
        DELETE FROM landing_data
        USING biz_state_matched
        WHERE id = biz_state_matched.current_version
    ),
    inserted_landing_data AS (
        INSERT INTO landing_data (
           name, categories, description, logo, cover, contacts, extras, preferences,
           blocks_options, photos, photo_settings, is_updated_from_geosearch, schedule
        )
        SELECT $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15
        FROM biz_state_matched
        RETURNING *
    ),
    updated_biz_state AS (
        UPDATE biz_state
        SET
            stable_version = (CASE WHEN $2 = 'STABLE' THEN inserted_landing_data.id ELSE stable_version END),
            unstable_version = (CASE WHEN $2 = 'UNSTABLE' THEN inserted_landing_data.id ELSE unstable_version END)
        FROM inserted_landing_data
        WHERE biz_id = $1
        RETURNING slug, published, permalink
    )
    SELECT
        slug,
        published,
        name,
        permalink,
        categories,
        description,
        logo,
        cover,
        contacts,
        extras,
        preferences,
        blocks_options,
        $2 AS version,
        landing_type,
        NULL AS instagram
    FROM updated_biz_state, inserted_landing_data
"""

delete_landing = """
    WITH
    biz_state_matched AS (
        SELECT
            stable_version,
            unstable_version
        FROM biz_state
        WHERE biz_id = $1
    ),
    deleted_landing_data AS (
        DELETE FROM landing_data
        USING biz_state_matched
        WHERE id IN (biz_state_matched.stable_version, biz_state_matched.unstable_version)
    )
    DELETE FROM biz_state
    WHERE biz_id = $1
    RETURNING TRUE
"""

fetch_landing_data_for_crm = """
    SELECT
        slug,
        permalink, 
        published,
        name,
        categories,
        description,
        logo,
        cover,
        contacts,
        extras,
        preferences,
        blocks_options,
        blocked,
        blocking_data,
        landing_type,
        is_updated_from_geosearch,
        NULL AS instagram
    FROM biz_state
    LEFT JOIN landing_data
        ON (
            CASE
                WHEN $2 = 'STABLE' THEN biz_state.stable_version
                WHEN $2 = 'UNSTABLE' THEN biz_state.unstable_version
            END
        ) = landing_data.id
    WHERE biz_id = $1
"""

fetch_landing_data = """
with found_aliases AS (
    select biz_id from slug_aliases where slug = $1 and expiration_date > now() limit 1
)
SELECT
        biz_state.biz_id as biz_id,
        name,
        biz_state.permalink as permalink,
        categories,
        description,
        logo,
        cover,
        contacts,
        extras,
        preferences,
        blocks_options,
        landing_type,
        instagram,
        chain_id,
        schedule,
        photos,
        photo_settings,
        is_updated_from_geosearch
    FROM biz_state
    JOIN landing_data ON (
        CASE $2
            WHEN 'STABLE' THEN biz_state.stable_version = landing_data.id
            WHEN 'UNSTABLE' THEN biz_state.unstable_version = landing_data.id
            ELSE FALSE
        END
    )
    WHERE biz_state.slug = $1
       OR biz_state.biz_id = (select biz_id from found_aliases)
"""

set_landing_publicity = """
    UPDATE biz_state
    SET published = $2
    WHERE biz_id = $1
"""

fetch_org_promos = """
    SELECT 
        announcement,
        description,
        TO_TIMESTAMP(CONCAT(date_from, ' 00:00:00'), 'YYYY-MM-DD HH24:MI:SS') as date_from,
        TO_TIMESTAMP(CONCAT(date_to, ' 23:59:59'), 'YYYY-MM-DD HH24:MI:SS') as date_to,
        banner_img,
        link as details_url
    FROM promotions
    WHERE biz_id = $1
    ORDER BY promotion_id DESC
"""

fetch_promoted_cta = """
    SELECT 
        title as custom,
        link as value
    FROM promoted_cta
    WHERE biz_id = $1
"""

fetch_promoted_services = """
    SELECT 
        service_id as id,
        title as name,
        cost,
        image,
        url,
        description
    FROM promoted_services
    WHERE service_id in (
        SELECT unnest(services)
        FROM promoted_service_lists
        WHERE biz_id = $1
    ) and biz_id = $1
    ORDER BY service_id
"""

fetch_substitution_phone = """
    SELECT formatted_phone
    FROM call_tracking
    WHERE biz_id = $1
"""

set_cached_landing_config = """
    UPDATE cached_landing_config SET data = $1
"""

create_instagram_landing = """
    with insert_landing as (
        insert into landing_data (landing_type, name, categories, contacts, instagram, preferences, logo, description)
        values ('INSTAGRAM', $3, '{}', $9, $4, $5, $6, $7)
        returning id
    )
    insert into biz_state (biz_id, slug, stable_version, published, permalink)
    select $1, $2, insert_landing.id, true, $8
    from insert_landing
"""

save_instagram_landing = """
    update landing_data set
        instagram = coalesce($2, instagram),
        preferences = preferences || coalesce($3, '{}'::jsonb),
        name = coalesce($4, name),
        description = coalesce($5, description),
        logo = coalesce($6, logo),
        contacts = coalesce($7, contacts)
    where id = $1
"""

fetch_avatars = """
    select source_url, avatars_group_id, avatars_name
    from avatars
    where source_url = any($1::text[])
"""

fetch_google_counters = """
    SELECT counter_data FROM google_counters WHERE permalink = $1
"""

fetch_tiktok_pixels = """
    SELECT pixel_data FROM tiktok_pixels WHERE permalink = $1
"""

fetch_vk_pixels = """
    SELECT pixel_data FROM vk_pixels WHERE permalink = $1
"""

fetch_landing_phone = """
    SELECT contacts->>'phone' FROM landing_data as d 
    JOIN biz_state as b on d.id = b.stable_version
    WHERE b.permalink = $1 and b.published and d.landing_type = 'DEFAULT'
"""

fetch_all_published_permalinks = """
    SELECT DISTINCT permalink FROM biz_state
    WHERE published OFFSET $1 LIMIT $2
"""

fetch_branches_for_permalink = """
    SELECT
        slug,
        name,
        permalink,
        description,
        logo,
        cover,
        contacts,
        schedule,
        preferences
    FROM biz_state
    JOIN landing_data ON (
        CASE $2
            WHEN 'STABLE' THEN biz_state.stable_version = landing_data.id
            WHEN 'UNSTABLE' THEN biz_state.unstable_version = landing_data.id
            ELSE FALSE
        END
    )
    WHERE 
        landing_data.landing_type = 'DEFAULT' and
        biz_state.permalink <> $1 and 
        landing_data.chain_id = $3 and 
        biz_state.published and 
        landing_data.is_updated_from_geosearch
    LIMIT $4
"""

fetch_landings_for_permalink = """
    SELECT id, contacts, preferences
    FROM landing_data
    WHERE 
    landing_type = 'DEFAULT' AND
    id in (
        select stable_version as b_id from biz_state
        where permalink = $1
        union all 
        select unstable_version as b_id from biz_state
        where permalink = $1
    ) 
"""

update_landing_data_with_geosearch = """
    UPDATE landing_data SET 
    chain_id = $2,
    contacts = $3,
    schedule = $4,
    photos = $5,
    preferences = $6,
    is_updated_from_geosearch = true
    where id = $1
"""

update_instagram_landing_data_with_geosearch = """
    UPDATE landing_data SET 
    contacts = contacts || jsonb_build_object('geo', $2::jsonb),
    preferences = preferences || jsonb_build_object('external_metrika_code', $3::text),
    is_updated_from_geosearch = true
    where id in (select unnest(ARRAY[stable_version, unstable_version]) from biz_state where permalink = $1)
    and landing_type = 'INSTAGRAM'
"""

fetch_landing_extra_data = """
    SELECT
        photos,
        photo_settings,
        preferences,
        contacts,
        schedule,
        is_updated_from_geosearch
    FROM biz_state
    LEFT JOIN landing_data
        ON (
            CASE
                WHEN $2 = 'STABLE' THEN biz_state.stable_version
                WHEN $2 = 'UNSTABLE' THEN biz_state.unstable_version
            END
        ) = landing_data.id
    WHERE biz_id = $1
"""


fetch_landing_photos = """
    SELECT
        photos,
        photo_settings
    FROM biz_state
    LEFT JOIN landing_data
        ON (
            CASE
                WHEN $2 = 'STABLE' THEN biz_state.stable_version
                WHEN $2 = 'UNSTABLE' THEN biz_state.unstable_version
            END
        ) = landing_data.id
    WHERE biz_id = $1
"""

hide_landing_photos = """
    UPDATE landing_data
    SET photo_settings = $3
    WHERE id = (
        SELECT
            (
                CASE
                    WHEN $2 = 'STABLE' THEN stable_version
                    WHEN $2 = 'UNSTABLE' THEN unstable_version
                END
            ) AS current_version
        FROM biz_state
        WHERE biz_id = $1
    )
"""

fetch_market_int_services = """
    SELECT service_data FROM market_int_services WHERE biz_id = $1
"""

fetch_goods_data = """
    SELECT categories FROM goods_data WHERE permalink = $1
"""

sync_permalinks = """
    WITH t AS (
        SELECT tmp.biz_id AS biz_id, tmp.permalink AS permalink
        FROM {tmp_table_name} tmp
        JOIN biz_state bs ON bs.biz_id = tmp.biz_id
        JOIN landing_data ld ON ld.id = bs.stable_version
        WHERE NOT ld.is_updated_from_geosearch)
    UPDATE biz_state bs
    SET permalink = t.permalink::text
    FROM t
    WHERE bs.biz_id = t.biz_id
"""
