DROP MATERIALIZED VIEW IF EXISTS adset_insights_flattened CASCADE;

CREATE MATERIALIZED VIEW adset_insights_flattened AS
SELECT 
    time,
    adset_id,
    campaign_id,
    account_id,
    impressions,
    clicks,
    spend,
    reach,
    ctr,
    cpc,
    cpm,
    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
FROM adset_insights;

-- Add indexes for common query patterns

CREATE INDEX idx_adset_insights_flat_campaign ON adset_insights_flattened(campaign_id);
CREATE INDEX idx_adset_insights_flat_date ON adset_insights_flattened(date_start, date_stop);


CREATE UNIQUE INDEX idx_adset_insights_flat_unique ON adset_insights_flattened(time, adset_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY adset_insights_flattened;


SELECT 
    date_start as time, 
    account_id,
	adset_id,
	campaign_id,
    SUM(impressions) AS impressions, 
    SUM(clicks) AS clicks,
    SUM(spend) AS spend, 
    AVG(frequency) as frequency,
    avg(cpc) as cpc,
    avg(cpm) as cpm,
    avg(cpp) as cpp,
    avg(ctr) as ctr

FROM meta.ads_insights
group by time, account_id, adset_id, campaign_id