SET search_path = social,public;

-- update triggers

-- 'pending' -> 'outgoing_opened' or 'outgoing_opened_experiment', 'pending' -> 'outgoing_closed'
--
CREATE OR REPLACE FUNCTION feedback_task_pending_update_trigger() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
BEGIN
    IF (NEW.bucket != 'outgoing') THEN
        RETURN NEW;
    END IF;

    IF (NEW.closed_by IS NULL) THEN

        IF (NEW.type IN ('address-experiment', 'entrance-experiment')) THEN
            INSERT INTO social.feedback_task_outgoing_opened_experiment VALUES (NEW.*);
        ELSE
            INSERT INTO social.feedback_task_outgoing_opened VALUES (NEW.*);
        END IF;

        -- update outgoing opened feed
        --
        INSERT INTO social.feedback_aoi_feed_outgoing_opened
            SELECT * FROM social.feedback_aoi_feed_pending WHERE feedback_task_id = NEW.id;

    ELSE

        INSERT INTO social.feedback_task_outgoing_closed VALUES (NEW.*);

        -- update outgoing closed feed
        --
        INSERT INTO social.feedback_aoi_feed_outgoing_closed
            SELECT * FROM social.feedback_aoi_feed_pending WHERE feedback_task_id = NEW.id;
    END IF;

    DELETE FROM social.feedback_task_pending WHERE id = NEW.id;
    DELETE FROM social.feedback_aoi_feed_pending WHERE feedback_task_id = NEW.id;

    RETURN NULL;
END;
$$;


-- 'outgoing_closed' -> 'outgoing_opened' or 'outgoing_opened_experiment'
--
CREATE OR REPLACE FUNCTION feedback_task_outgoing_closed_update_trigger() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
BEGIN
    IF (NEW.closed_by IS NOT NULL) THEN
        RETURN NEW;
    END IF;

    DELETE FROM social.feedback_task_outgoing_closed WHERE id = OLD.id;

    IF (NEW.type IN ('address-experiment', 'entrance-experiment')) THEN
        INSERT INTO social.feedback_task_outgoing_opened_experiment VALUES (NEW.*);
    ELSE
        INSERT INTO social.feedback_task_outgoing_opened VALUES (NEW.*);
    END IF;

    -- update outgoing opened feed
    --
    INSERT INTO social.feedback_aoi_feed_outgoing_opened
        SELECT * FROM social.feedback_aoi_feed_outgoing_closed WHERE feedback_task_id = NEW.id;
    DELETE FROM social.feedback_aoi_feed_outgoing_closed WHERE feedback_task_id = NEW.id;

    RETURN NULL;
END;
$$;


SET search_path=public;
