-- 'closed' -> NULL
--
DROP MATERIALIZED VIEW IF EXISTS social.feedback_task_distinct_source_type_mv;


CREATE MATERIALIZED VIEW social.feedback_task_distinct_source_type_mv AS
SELECT
    source,
    type,
    hidden,
    workflow,
    CASE WHEN resolved_by IS NOT NULL THEN 'resolved'
         WHEN bucket = 'need-info' THEN 'need-info'
         ELSE 'opened'
    END AS status,
    min(state_modified_at) AS min_created_at,
    max(state_modified_at) AS max_created_at
FROM social.feedback_task
WHERE
    bucket NOT IN ('incoming', 'deferred')
GROUP BY
    source,
    type,
    hidden,
    workflow,
    status
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_task_distinct_source_type_mv_idx
ON social.feedback_task_distinct_source_type_mv
(source, type, hidden, workflow, status, min_created_at, max_created_at);

