START TRANSACTION;

CREATE TYPE abc_role_sync_type AS ENUM ('MEMBER', 'RESPONSIBLE', 'ROLE', 'NONE');

CREATE TABLE IF NOT EXISTS project_role
(
    id                 bigserial PRIMARY KEY,
    key                short_text         NOT NULL UNIQUE,
    abc_role_sync_type abc_role_sync_type NOT NULL,
    abc_role_id        integer UNIQUE,
    constraint abc_role check (
            (abc_role_sync_type = 'ROLE' AND abc_role_id IS NOT NULL) OR
            (abc_role_sync_type <> 'ROLE' AND abc_role_id IS NULL)
        )
);

COMMENT ON TABLE project_role IS 'Person roles in projects';

CREATE INDEX IF NOT EXISTS project_role_key_idx ON project_role (key);

INSERT INTO project_role (id, key, abc_role_sync_type, abc_role_id)
VALUES (0, 'RESPONSIBLE', 'NONE', null),
       (1, 'MEMBER', 'NONE', null);

ALTER TABLE person_membership
    ADD COLUMN project_role_id bigint REFERENCES project_role (id);

UPDATE person_membership
SET project_role_id = 0
WHERE role = 'RESPONSIBLE';

UPDATE person_membership
SET project_role_id = 1
WHERE role = 'MEMBER';

ALTER TABLE person_membership
    ALTER COLUMN project_role_id SET NOT NULL;

ALTER TABLE person_membership
    DROP CONSTRAINT person_membership_pkey;

ALTER TABLE person_membership ADD PRIMARY KEY (person_id, project_id, project_role_id);

ALTER TABLE person_membership
    ALTER COLUMN role DROP NOT NULL;


ALTER TABLE yandex_group_membership
    ADD COLUMN project_role_id bigint REFERENCES project_role (id);

UPDATE yandex_group_membership
SET project_role_id = 0
WHERE role = 'RESPONSIBLE';

UPDATE yandex_group_membership
SET project_role_id = 1
WHERE role = 'MEMBER';

ALTER TABLE yandex_group_membership
    ALTER COLUMN project_role_id SET NOT NULL;

ALTER TABLE yandex_group_membership
    DROP CONSTRAINT yandex_group_membership_pkey;

ALTER TABLE yandex_group_membership ADD PRIMARY KEY (yandex_group_id, project_id, project_role_id);

ALTER TABLE yandex_group_membership
    ALTER COLUMN role DROP NOT NULL;

COMMIT;
