--- campaign insights by country

DROP MATERIALIZED VIEW IF EXISTS campaign_insights_by_country_flattened CASCADE;

CREATE MATERIALIZED VIEW campaign_insights_by_country_flattened AS
 SELECT date_start AS "time",
    concat('act_', account_id) AS account_id,
    campaign_id,
    country,
    impressions,
    clicks,
    spend,
    reach,
    frequency,
    ctr,
    cpc,
    cpm,
    date_start,
    date_stop,
    (SELECT (value->>'value')::numeric
     FROM jsonb_array_elements(actions)
     WHERE value->>'action_type' = 'link_click') AS link_click,
    (SELECT (value->>'value')::numeric
     FROM jsonb_array_elements(actions)
     WHERE value->>'action_type' = 'landing_page_view') AS landing_page_view,
    (SELECT (value->>'value')::numeric
     FROM jsonb_array_elements(actions)
     WHERE value->>'action_type' = 'lead') AS lead

   FROM meta.custom_campaign_country;

CREATE INDEX idx_campaign_insights_by_country_flat_date ON campaign_insights_by_country_flattened(date_start, date_stop);

CREATE UNIQUE INDEX idx_campaign_insights_by_country_flat_unique ON campaign_insights_by_country_flattened(time, campaign_id, country);

REFRESH MATERIALIZED VIEW CONCURRENTLY campaign_insights_by_country_flattened;
