START TRANSACTION;

ALTER TABLE person ALTER COLUMN uid SET NOT NULL;

ALTER TABLE person ADD CONSTRAINT person_uid_unique_constraint UNIQUE (uid);

DROP INDEX IF EXISTS person_uid_unique;

DELETE FROM yandex_group_membership WHERE yandex_group_id IN (SELECT id FROM yandex_group WHERE url_acceptable_key = 'ex-staff');
DELETE FROM yandex_group_membership WHERE yandex_group_id IN (SELECT id FROM yandex_group WHERE url_acceptable_key = 'robot-videofresh');
DELETE FROM yandex_group_membership WHERE yandex_group_id IN (SELECT id FROM yandex_group WHERE url_acceptable_key = 'robot-imgfresh');

DELETE FROM yandex_group WHERE url_acceptable_key = 'ex-staff';
DELETE FROM yandex_group WHERE url_acceptable_key = 'robot-videofresh';
DELETE FROM yandex_group WHERE url_acceptable_key = 'robot-imgfresh';

ALTER TABLE yandex_group ADD COLUMN IF NOT EXISTS staff_id bigint;
ALTER TABLE yandex_group ADD COLUMN IF NOT EXISTS deleted boolean;

CREATE UNIQUE INDEX IF NOT EXISTS yandex_group_staff_id_unique ON yandex_group (staff_id) WHERE staff_id IS NOT NULL;

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'person_affiliation') THEN
        CREATE TYPE person_affiliation AS ENUM ('UNKNOWN', 'YANDEX', 'YA_MONEY', 'EXTERNAL');
    END IF;
END$$;

ALTER TABLE person ADD COLUMN IF NOT EXISTS is_robot boolean;
ALTER TABLE person ADD COLUMN IF NOT EXISTS is_dismissed boolean;
ALTER TABLE person ADD COLUMN IF NOT EXISTS is_deleted boolean;
ALTER TABLE person ADD COLUMN IF NOT EXISTS affiliation person_affiliation;

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'person_group_membership_type') THEN
        CREATE TYPE person_group_membership_type AS ENUM ('DEPARTMENT', 'DEPARTMENT_ANCESTORS', 'GROUP');
    END IF;
END$$;

CREATE TABLE IF NOT EXISTS person_group_membership (
    id BIGSERIAL PRIMARY KEY,
    person_id BIGINT NOT NULL REFERENCES person (id) ON UPDATE CASCADE ON DELETE CASCADE,
    group_id BIGINT NOT NULL REFERENCES yandex_group (id) ON UPDATE CASCADE ON DELETE CASCADE,
    membership_type person_group_membership_type NOT NULL,
    UNIQUE (person_id, group_id, membership_type)
);

COMMENT ON TABLE person_group_membership IS 'Membership of persons in groups';

COMMIT;