CREATE TABLE IF NOT EXISTS public.typing_status
(
    chatid uuid NOT NULL,
    userid uuid NOT NULL,
    username text NOT NULL,
    last_ping timestamp without time zone NOT NULL DEFAULT now()
);

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint
    WHERE conname = 'typing_status_pkey'
    AND conrelid = 'public.typing_status'::regclass
  ) THEN
    ALTER TABLE public.typing_status
    ADD CONSTRAINT typing_status_pkey PRIMARY KEY (chatid,userid);
  END IF;
END $$;

DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'typing_user'
    AND conrelid = 'public.typing_status'::regclass
    ) THEN
        ALTER TABLE public.typing_status 
        ADD CONSTRAINT typing_user 
        FOREIGN KEY (userid) REFERENCES public.users (id) 
        ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $$;

DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'typing_chat'
    AND conrelid = 'public.typing_status'::regclass
    ) THEN
        ALTER TABLE public.typing_status 
        ADD CONSTRAINT typing_chat 
        FOREIGN KEY (chatid) REFERENCES public.chats (chatid) 
        ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $$;



CREATE INDEX IF NOT EXISTS typing_status_chat_lastping_idx 
ON typing_status (chatid, last_ping DESC);