SET search_path = social,public;

CREATE TABLE deferred_task (
    event_id bigserial NOT NULL CHECK (event_id > 0),
    deferred_by bigint NOT NULL CHECK (deferred_by > 0),
    deferred_at timestamp with time zone NOT NULL DEFAULT NOW(),
    expires_at timestamp with time zone NOT NULL
);

CREATE INDEX deferred_task_event_id_deferred_by_expires_at_idx
    ON deferred_task USING btree (event_id, deferred_by, expires_at);


CREATE OR REPLACE FUNCTION task_active_update_trigger() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
BEGIN
    IF (NEW.close_resolution IS NULL) THEN
        RETURN NEW;
    END IF;
    DELETE FROM social.deferred_task WHERE event_id = OLD.event_id;
    DELETE FROM social.task_active WHERE event_id = OLD.event_id;
    INSERT INTO social.task_closed VALUES (NEW.*);
    RETURN NULL;
END;
$$;

SET search_path = public;
