CREATE TABLE IF NOT EXISTS public.messages_attachments
(
    "messageId" uuid NOT NULL,
    "userStorageId" uuid NOT NULL
);

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint
    WHERE conname = 'messages_attachments_pkey'
    AND conrelid = 'public.messages_attachments'::regclass
  ) THEN
    ALTER TABLE public.messages_attachments
    ADD CONSTRAINT messages_attachments_pkey PRIMARY KEY ("messageId", "userStorageId");
  END IF;
END $$;


DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'msg_attach_msgid'
    AND conrelid = 'public.messages_attachments'::regclass
    ) THEN
        ALTER TABLE public.messages_attachments 
        ADD CONSTRAINT msg_attach_msgid 
        FOREIGN KEY ("messageId") REFERENCES public.messages (messageid) 
        ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $$;

DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'msg_attach_storageid'
    AND conrelid = 'public.messages_attachments'::regclass
    ) THEN
        ALTER TABLE public.messages_attachments 
        ADD CONSTRAINT msg_attach_storageid 
        FOREIGN KEY ("userStorageId") REFERENCES public.users_storage (user_storage_id) 
        ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $$;