/* pgmigrate-encoding: utf-8 */
CREATE SCHEMA idm;

CREATE TABLE idm.project(
    id bigserial PRIMARY KEY,
    key text NOT NULL UNIQUE,
    name_ru text NOT NULL,
    name_en text NOT NULL,
    slug text NOT NULL,
    slug_name_ru text NOT NULL,
    slug_name_en text NOT NULL,
    parent_id bigint REFERENCES idm.project(id),

    CONSTRAINT idm_project_slug_allowed_characters CHECK(lower(slug) SIMILAR TO '([a-z]|[0-9]|\_|-)*')
);


CREATE TABLE idm.role(
    id bigserial PRIMARY KEY,
    key text NOT NULL,
    name_ru text NOT NULL,
    name_en text NOT NULL,
    role_set text
);


CREATE TABLE idm.project_role(
    id bigserial PRIMARY KEY,
    project_id bigint REFERENCES idm.project(id),
    role_id bigint REFERENCES idm.role(id),
    UNIQUE(project_id, role_id)
);


CREATE TABLE idm.user_role(
    login text,
    project_role_id bigint REFERENCES idm.project_role(id),
    PRIMARY KEY(login, project_role_id)
);

-- Create root project
INSERT INTO idm.project(key, name_ru, name_en, slug, slug_name_ru, slug_name_en)
VALUES('_root', 'Система', 'System', 'project', 'Выберите проект', 'Select project');
