START TRANSACTION;

CREATE TYPE quota_request_history_event_type AS ENUM('CREATE', 'FIELDS_UPDATE', 'STATUS_UPDATE', 'CHANGES_UPDATE', 'BATCH_STATUS_UPDATE',
 'ISSUE_KEY_UPDATE', 'PROJECT_UPDATE', 'SERVICE_UPDATE', 'READY_FOR_ALLOCATION_STATE_UPDATE', 'CHANGES_READY_AMOUNT_UPDATE', 'CHANGES_ALLOCATED_AMOUNT_UPDATE');

CREATE TABLE IF NOT EXISTS quota_request_history
(
    id BIGSERIAL PRIMARY KEY,
    quota_request_id BIGINT NOT NULL REFERENCES quota_request (id) ON UPDATE CASCADE ON DELETE CASCADE,
    event_type quota_request_history_event_type NOT NULL,
    person_id BIGINT REFERENCES person (id) ON UPDATE CASCADE ON DELETE CASCADE,
    tvm_id BIGINT,
    comment TEXT,
    updated timestamp NOT NULL,
    old_data JSONB NOT NULL,
    new_data JSONB NOT NULL,
    CONSTRAINT person_id_or_tvm_id_is_not_null CHECK (person_id IS NOT NULL OR tvm_id IS NOT NULL)
);

CREATE TABLE IF NOT EXISTS quota_history
(
    id BIGSERIAL PRIMARY KEY,
    quota_id BIGINT NOT NULL REFERENCES quota (id) ON UPDATE CASCADE ON DELETE CASCADE,
    person_id BIGINT REFERENCES person (id) ON DELETE CASCADE ON UPDATE CASCADE,
    tvm_id BIGINT,
    comment TEXT,
    updated timestamp NOT NULL,
    old_max BIGINT NOT NULL,
    new_max BIGINT NOT NULL,
    old_own_max BIGINT NOT NULL,
    new_own_max BIGINT NOT NULL,
    issue_key short_text,
    CONSTRAINT person_id_or_tvm_id_is_not_null CHECK (person_id IS NOT NULL OR tvm_id IS NOT NULL)
);

COMMENT ON TABLE quota_request_history IS 'History of quota requests changes';
COMMENT ON TABLE quota_history IS 'History of quota maxes changes';

CREATE INDEX IF NOT EXISTS quota_history_quota_id_ix ON quota_history (quota_id);
CREATE INDEX IF NOT EXISTS quota_history_person_id_ix ON quota_history (person_id);
CREATE INDEX IF NOT EXISTS quota_history_updated_ix ON quota_history (updated);
CREATE INDEX IF NOT EXISTS quota_request_history_quota_request_id_ix ON quota_request_history (quota_request_id);
CREATE INDEX IF NOT EXISTS quota_request_history_person_id_ix ON quota_request_history (person_id);
CREATE INDEX IF NOT EXISTS quota_request_history_updated_ix ON quota_request_history (updated);

COMMIT;