-- User Storage
CREATE TABLE IF NOT EXISTS public.users_storage (
    "userId" UUID NOT NULL,
    "storageId" TEXT NOT NULL,
    from_admin boolean DEFAULT FALSE NOT NULL,
    user_storage_id UUID DEFAULT gen_random_uuid () NOT NULL
);
-- Primary Key
DO $$
BEGIN
    ALTER TABLE public.users_storage 
    ADD CONSTRAINT users_storage_pkey PRIMARY KEY (user_storage_id);
EXCEPTION   
    WHEN invalid_table_definition THEN
        RAISE NOTICE 'Primary key already exists. Ignoring...';
END $$;
-- Unique UserId and StorageId
DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'users_storage_user_storage_key'
    ) THEN
        ALTER TABLE public.users_storage 
        ADD CONSTRAINT users_storage_user_storage_key UNIQUE ("userId", "storageId");
    END IF;
END $$;
-- Foreign Key to Users
DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'userstorage'
    ) THEN
        ALTER TABLE public.users_storage 
        ADD CONSTRAINT userstorage 
        FOREIGN KEY ("userId") REFERENCES public.users (id) 
        ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $$;