DROP MATERIALIZED VIEW IF EXISTS account_insights_flattened CASCADE;

CREATE MATERIALIZED VIEW account_insights_flattened AS
SELECT
    time,
    account_id,
    impressions,
    clicks,
    spend,
    reach,
    frequency,
    ctr,
    cpc,
    cpm,
    cpp,
    date_preset,
    date_start,
    date_stop,
    fetched_at,
    (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,
    (SELECT (value->>'value')::numeric
     FROM jsonb_array_elements(cost_per_action_type)
     WHERE value->>'action_type' = 'link_click') AS cost_per_link_click,
    (SELECT (value->>'value')::numeric
     FROM jsonb_array_elements(cost_per_action_type)
     WHERE value->>'action_type' = 'landing_page_view') AS cost_per_landing_page_view,
    (SELECT (value->>'value')::numeric
     FROM jsonb_array_elements(cost_per_action_type)
     WHERE value->>'action_type' = 'lead') AS cost_per_lead
FROM account_insights;

CREATE INDEX idx_account_insights_flat_date ON account_insights_flattened(date_start, date_stop);

CREATE UNIQUE INDEX idx_account_insights_flat_unique ON account_insights_flattened(time, account_id);

REFRESH MATERIALIZED VIEW CONCURRENTLY account_insights_flattened;
