create_campaign = """
    WITH campaigns_rows AS (
        INSERT INTO campaign (
            name,
            author_id,
            publication_envs,
            campaign_type,
            start_datetime,
            end_datetime,
            timezone,
            billing_id,
            platforms,
            order_id,
            manul_order_id,
            comment,
            targeting,
            rubric,
            order_size,
            user_daily_display_limit,
            user_display_limit,
            datatesting_expires_at,
            settings
        )
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
        RETURNING id
    ), status_rows AS (
        INSERT INTO status_history (campaign_id, author_id, status)
        SELECT id, $2, $20
        FROM campaigns_rows
    )
    SELECT * FROM campaigns_rows
"""  # noqa: E501

retrieve_campaign = """
    SELECT
        campaign.id,
        campaign.author_id,
        campaign.name,
        campaign.publication_envs,
        campaign.campaign_type,
        campaign.start_datetime,
        campaign.end_datetime,
        campaign.timezone,
        campaign.platforms,
        campaign.order_id,
        campaign.manul_order_id,
        campaign.comment,
        campaign.user_display_limit,
        campaign.user_daily_display_limit,
        campaign.targeting,
        campaign.rubric,
        campaign.order_size,
        campaign.datatesting_expires_at,
        campaign.settings,
        -- Billing data
        (
            CASE
            WHEN campaign_billing.cpm_id IS NOT NULL THEN 'cpm'
            WHEN campaign_billing.cpa_id IS NOT NULL THEN 'cpa'
            WHEN campaign_billing.fix_id IS NOT NULL THEN 'fix'
            END
        ) AS _billing_type,
        billing_cpm.cost AS _cpm_cost,
        billing_cpm.budget AS _cpm_budget,
        billing_cpm.daily_budget AS _cpm_daily_budget,
        billing_cpm.auto_daily_budget AS _cpm_auto_daily_budget,
        billing_cpa.cost AS _cpa_cost,
        billing_cpa.budget AS _cpa_budget,
        billing_cpa.daily_budget AS _cpa_daily_budget,
        billing_cpa.auto_daily_budget AS _cpa_auto_daily_budget,
        billing_fix.cost AS _fix_cost,
        billing_fix.time_interval AS _fix_time_interval,
        coalesce(actions_subq.actions, '[]'::jsonb) AS actions,
        coalesce(creatives_subq.creatives, '[]'::jsonb) AS creatives,
        (
            '{}'::jsonb
            || coalesce(placing_organizations_subq.places::jsonb, '{}'::jsonb)
            || coalesce(placing_areas_subq.places::jsonb, '{}'::jsonb)
        ) AS "placing",
        coalesce(week_schedule_subq.schedules, '[]'::jsonb) AS week_schedule,
        status_subq.status AS status,
        creation_date_subq.changed_datetime AS created_datetime,
        campaign_direct_moderation.verdicts as moderation_verdicts,
        campaign.direct_moderation_id,
        campaign.paid_till
    FROM campaign
    LEFT JOIN campaign_billing ON campaign.billing_id = campaign_billing.id
    LEFT JOIN billing_cpm ON campaign_billing.cpm_id = billing_cpm.id
    LEFT JOIN billing_cpa ON campaign_billing.cpa_id = billing_cpa.id
    LEFT JOIN billing_fix ON campaign_billing.fix_id = billing_fix.id
    LEFT JOIN action_search ON campaign.id = action_search.campaign_id
    -- Actions
    LEFT JOIN (
        SELECT jsonb_agg(data) AS actions
        FROM (
            SELECT
                jsonb_build_object(
                    'type_', 'search',
                    'title', title,
                    'organizations', organizations,
                    'history_text', history_text,
                    'main', main
                ) AS data
            FROM action_search
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'open_site',
                    'title', title,
                    'url', url,
                    'main', main
                ) AS data
            FROM action_open_site
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'phone_call',
                    'title', title,
                    'phone', phone,
                    'main', main
                ) AS data
            FROM action_phone_call
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'download_app',
                    'title', title,
                    'google_play_id', google_play_id,
                    'app_store_id', app_store_id,
                    'url', url,
                    'main', main
                ) AS data
            FROM action_download_app
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'promocode',
                    'promocode', promocode,
                    'main', main
                ) AS data
            FROM action_promocode
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'resolve_uri',
                    'uri', uri,
                    'action_type', action_type,
                    'target', target,
                    'dialog', dialog,
                    'main', main
                ) AS data
            FROM action_resolve_uri
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'add_point_to_route',
                    'latitude', latitude,
                    'longitude', longitude,
                    'main', main
                ) AS data
            FROM action_add_point_to_route
            WHERE campaign_id = $1
        ) AS gather_actions_subq
    ) AS actions_subq ON TRUE
    -- Creatives
    LEFT JOIN (
        SELECT jsonb_agg(data) AS creatives
        FROM (
            SELECT
                jsonb_build_object(
                    'type_', 'pin',
                    'images', images,
                    'title', title,
                    'subtitle', subtitle
                ) AS data
            FROM creative_pin
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'billboard',
                    'images', images,
                    'images_v2', images_v2,
                    'title', title,
                    'description', description
                ) AS data
            FROM creative_billboard
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'icon',
                    'images', images,
                    'position', position,
                    'title', title
                ) AS data
            FROM creative_icon
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'pin_search',
                    'images', images,
                    'title', title,
                    'organizations', organizations
                ) AS data
            FROM creative_pin_search
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'logo_and_text',
                    'images', images,
                    'text', text
                ) AS data
            FROM creative_logo_and_text
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'text',
                    'text', text,
                    'disclaimer', disclaimer
                ) AS data
            FROM creative_text
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'via_point',
                    'images', images,
                    'button_text_active', button_text_active,
                    'button_text_inactive', button_text_inactive,
                    'description', description
                ) AS data
            FROM creative_via_point
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'banner',
                    'images', images,
                    'disclaimer', disclaimer,
                    'show_ads_label', show_ads_label,
                    'description', description,
                    'title', title,
                    'terms', terms
                ) AS data
            FROM creative_banner
            WHERE campaign_id = $1

            UNION ALL

            SELECT
                jsonb_build_object(
                    'type_', 'audio_banner',
                    'images', images,
                    'left_anchor', left_anchor,
                    'audio_file_url', audio_file_url
                ) AS data
            FROM creative_audio_banner
            WHERE campaign_id = $1
        ) AS gather_creatives_subq
    ) AS creatives_subq ON TRUE
    -- Placing
    LEFT JOIN (
        SELECT
            jsonb_build_object(
                'organizations',
                jsonb_build_object('permalinks', permalinks)
            ) AS places
        FROM campaign_placing_organizations
        WHERE campaign_id = $1
    ) AS placing_organizations_subq ON TRUE
    LEFT JOIN (
        SELECT
            jsonb_build_object(
                'area',
                jsonb_build_object(
                    'areas', areas,
                    'version', version
                )
            ) AS places
        FROM campaign_placing_area
        WHERE campaign_id = $1
    ) AS placing_areas_subq ON TRUE
    -- Week schedule
    LEFT JOIN (
        SELECT jsonb_agg(json_build_object('start', "start", 'end', "end")) AS schedules
        FROM campaign_week_schedule
        WHERE campaign_id = $1
    ) AS week_schedule_subq ON TRUE
    -- Status
    LEFT JOIN (
        SELECT DISTINCT ON (campaign_id) status
        FROM status_history
        WHERE campaign_id = $1
        ORDER BY campaign_id, changed_datetime DESC
    ) AS status_subq ON TRUE
    LEFT JOIN (
        SELECT changed_datetime
        FROM status_history
        WHERE campaign_id = $1
        ORDER BY changed_datetime
        LIMIT 1
    ) AS creation_date_subq ON TRUE
    LEFT JOIN campaign_direct_moderation
        ON campaign.direct_moderation_id = campaign_direct_moderation.id
    WHERE campaign.id = $1
"""

insert_campaign_status_history_entry = """
    INSERT INTO status_history (campaign_id, author_id, status, metadata)
    VALUES ($1, $2, $3, $4)
"""

campaign_exists = """
    SELECT EXISTS (
        SELECT 1
        FROM campaign
        WHERE id = $1
    )
"""

retrieve_campaign_status = """
    SELECT status
    FROM status_history
    WHERE campaign_id = $1
    ORDER BY changed_datetime DESC
    LIMIT 1
"""

insert_campaigns_change_log = """
WITH reset_latest_marker AS (
    UPDATE campaigns_change_log
    SET is_latest=FALSE
    WHERE campaign_id=$1 AND is_latest = TRUE
)

INSERT INTO campaigns_change_log (
    campaign_id,
    author_id,
    status,
    system_metadata,
    state_before,
    state_after,
    is_latest
)
    SELECT
        id                                  AS campaign_id,
        $2::bigint                          AS author_id,
        current_status_history ->> 'status' AS status,
        $3::jsonb                           AS system_metadata,
        '{}'::jsonb                         AS state_before,
        to_jsonb(campaigns_full_state_view) AS state_after,
        TRUE                                AS is_latest
    FROM campaigns_full_state_view
    WHERE id=$1

RETURNING id
"""

refresh_campaigns_change_logs_status_and_states = """
UPDATE campaigns_change_log
SET
    state_before=state_after,
    (state_after, status) = (  -- Сопоставление идет по позициям, а не по именам
        SELECT
            to_jsonb(campaigns_full_state_view) AS state_after,
            current_status_history->>'status' AS status
        FROM campaigns_full_state_view
        WHERE id=campaigns_change_log.campaign_id
    )
WHERE id = ANY($1::bigint[])
RETURNING id
"""

set_direct_moderation_for_campaign = (
    "UPDATE campaign SET direct_moderation_id = $2 WHERE id = $1"
)

update_paid_till = """
UPDATE campaign SET paid_till = $2
WHERE id = $1
"""
