CREATE TABLE IF NOT EXISTS identity.users
(
    id uuid NOT NULL DEFAULT uuid_generate_v4(),
    username character varying NOT NULL,
    "password" character varying NOT NULL,
    email character varying NOT NULL,
    created_at timestamp without time zone NOT NULL DEFAULT now(),
    updated_at timestamp without time zone,
    PRIMARY KEY (id),
    UNIQUE (email),
    UNIQUE (username)
);

CREATE TABLE IF NOT EXISTS identity.roles
(
    id uuid NOT NULL DEFAULT uuid_generate_v4(),
    name character varying(100) COLLATE pg_catalog."default" NOT NULL,
    display_name character varying(200) COLLATE pg_catalog."default" NOT NULL,
    created_at timestamp without time zone NOT NULL DEFAULT now(),
    updated_at timestamp without time zone,
    PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS identity.users_roles
(
    id uuid NOT NULL DEFAULT uuid_generate_v4(),
    user_id uuid NOT NULL,
    role_id uuid NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY (user_id)
        REFERENCES identity.users (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    FOREIGN KEY (role_id)
        REFERENCES identity.roles (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID
    UNIQUE (user_id, role_id)
);

CREATE TABLE identity.url_access
(
    id uuid NOT NULL DEFAULT uuid_generate_v4(),
    roles json NOT NULL,
    url character varying(255) NOT NULL,
    method character varying(10) NOT NULL,
    service character varying(100) NOT NULL,
    PRIMARY KEY (id),
    UNIQUE (url, method, service)
);


ALTER TABLE IF EXISTS identity.users OWNER to egommerce;
ALTER TABLE IF EXISTS identity.roles OWNER to egommerce;
ALTER TABLE IF EXISTS identity.users_roles OWNER to egommerce;
ALTER TABLE IF EXISTS identity.url_access OWNER to egommerce;
