--- campaign insights

DROP MATERIALIZED VIEW IF EXISTS campaign_insights_flattened CASCADE;

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

CREATE INDEX idx_campaign_insights_flat_date ON campaign_insights_flattened(date_start, date_stop);

CREATE UNIQUE INDEX idx_campaign_insights_flat_unique ON campaign_insights_flattened(time, campaign_id);

REFRESH MATERIALIZED VIEW CONCURRENTLY campaign_insights_flattened;
