CREATE TABLE IF NOT EXISTS public.user_spaces
(
    Id         SERIAL PRIMARY KEY,
    Name       VARCHAR(255) NOT NULL,
    OwnerId    INT          NOT NULL REFERENCES administration.users (Id),
    -- for history
    Deleted    BOOLEAN      NOT NULL DEFAULT FALSE,
    EditorId   INT          NULL REFERENCES administration.users (Id),
    Created timestamptz  NOT NULL DEFAULT NOW(),
    Updated timestamptz  NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS public.user_spaces_history
(
    LIKE public.user_spaces
);

CREATE TRIGGER user_spaces_history_trigger
    BEFORE INSERT OR UPDATE OR DELETE
    ON public.user_spaces
    FOR EACH ROW
EXECUTE FUNCTION public.history_trigger_function();

CREATE TABLE IF NOT EXISTS public.user_spaces_users
(
    Id          SERIAL PRIMARY KEY,
    UserSpaceId INT         NOT NULL REFERENCES public.user_spaces (Id),
    UserId      INT         NOT NULL REFERENCES administration.users (Id),
    -- for history
    Deleted     BOOLEAN     NOT NULL DEFAULT FALSE,
    EditorId    INT         NULL REFERENCES administration.users (Id),
    Created  timestamptz NOT NULL DEFAULT NOW(),
    Updated  timestamptz NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS public.user_spaces_users_history
(
    LIKE public.user_spaces_users
);

CREATE TRIGGER user_spaces_users_history_trigger
    BEFORE INSERT OR UPDATE OR DELETE
    ON public.user_spaces_users
    FOR EACH ROW
EXECUTE FUNCTION public.history_trigger_function();

-- add user spaces
INSERT INTO public.user_spaces (Name, OwnerId)
VALUES ('Default', (SELECT id FROM administration.users ORDER BY id LIMIT 1));

INSERT INTO public.user_spaces_users (UserSpaceId, UserId)
SELECT 1 AS UserSpaceId, u.id AS UserId
FROM administration.users u
WHERE u.deleted = FALSE;

-- change other tables
ALTER TABLE public.groups
    ADD COLUMN IF NOT EXISTS UserSpaceId INT NOT NULL REFERENCES public.user_spaces (Id) default 1;

ALTER TABLE public.groups
    DROP COLUMN IF EXISTS UserId;

ALTER TABLE public.groups_history
    ADD COLUMN IF NOT EXISTS UserSpaceId INT NOT NULL REFERENCES public.user_spaces (Id) default 1;

ALTER TABLE public.groups_history
    DROP COLUMN IF EXISTS UserId;

ALTER TABLE public.short_urls
    ADD COLUMN IF NOT EXISTS UserSpaceId INT NOT NULL REFERENCES public.user_spaces (Id) default 1;

ALTER TABLE public.short_urls
    DROP COLUMN IF EXISTS UserId;

ALTER TABLE public.short_urls_history
    ADD COLUMN IF NOT EXISTS UserSpaceId INT NOT NULL REFERENCES public.user_spaces (Id) default 1;

ALTER TABLE public.short_urls_history
    DROP COLUMN IF EXISTS UserId;