--- campaign insights by country

DROP MATERIALIZED VIEW IF EXISTS campaign_insights_by_gender_and_age CASCADE;

CREATE MATERIALIZED VIEW campaign_insights_by_gender_and_age AS
SELECT date_start AS "time",
    concat('act_', account_id) AS account_id,
    campaign_id,
    gender,
	  age,
    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_gender;

CREATE INDEX idx_campaign_insights_by_gender_and_age_date ON campaign_insights_by_gender_and_age(date_start, date_stop);

CREATE UNIQUE INDEX idx_campaign_insights_by_gender_and_age_unique ON campaign_insights_by_gender_and_age(time, campaign_id, gender, age);
REFRESH MATERIALIZED VIEW CONCURRENTLY campaign_insights_by_gender_and_age;


DROP VIEW IF EXISTS campaign_insights_by_gender CASCADE;

create view campaign_insights_by_gender as 
Select time, 
sum(clicks) as clicks, 
sum(link_click) as link_click,
sum(lead) as lead,
sum(landing_page_view) as landing_page_view,
sum(spend) as spend, 
sum(reach) as reach, 
sum(impressions) as impressions, 
gender,
campaign_id,
account_id 
from campaign_insights_by_gender_and_age 
group by time, gender, account_id, campaign_id, date_start, date_stop;

DROP VIEW IF EXISTS campaign_insights_by_age CASCADE;

create view campaign_insights_by_age as 
Select time, 
sum(clicks) as clicks, 
sum(link_click) as link_click,
sum(lead) as lead,
sum(landing_page_view) as landing_page_view,
sum(spend) as spend, 
sum(reach) as reach, 
sum(impressions) as impressions, 
age,
campaign_id,
account_id 
from campaign_insights_by_gender_and_age 
group by time, age, account_id, campaign_id, date_start, date_stop;