CREATE MATERIALIZED VIEW social.feedback_aoi_opened_task_stat_mv AS
(
    SELECT
        aoi_id,
        source,
        type,
        workflow,
        COUNT(*) AS total,
        COUNT(*) FILTER (WHERE hidden = TRUE) as total_hidden,
        COUNT(*) FILTER (WHERE workflow = 'feedback' AND created_at <= now() - '24 hours'::interval) AS old,
        COUNT(*) FILTER (WHERE workflow = 'feedback' AND created_at <= now() - '24 hours'::interval AND hidden = TRUE) AS old_hidden
    FROM
        social.feedback_aoi_feed_outgoing_opened aoi
            JOIN
        social.feedback_task_outgoing_opened fb
            ON aoi.feedback_task_id = fb.id
    WHERE duplicate_head_id IS NULL
    GROUP BY
        aoi_id,
        source,
        type,
        workflow
)
WITH DATA;

-- In order to refresh this matview concurrently we must create unique index.
-- Refresh call is executed periodically in schedule_feedback_worker

CREATE UNIQUE INDEX feedback_aoi_opened_task_stat_mv_idx
ON social.feedback_aoi_opened_task_stat_mv
(aoi_id, source, type, workflow, total, total_hidden, old, old_hidden);
