CREATE EXTENSION IF NOT EXISTS "pgcrypto";

CREATE TABLE public.faq_replies (
    id uuid NOT NULL,
    faq_id uuid NOT NULL,
    study_id uuid,
    content text NOT NULL,
    created_by uuid NOT NULL,
    created_at timestamp with time zone DEFAULT now() NOT NULL,
    quote_reply_id uuid
);

ALTER TABLE public.faq_replies OWNER TO ctms_user;

ALTER TABLE ONLY public.faq_replies
    ADD CONSTRAINT faq_replies_pkey PRIMARY KEY (id);

CREATE INDEX ix_faq_replies_faq_id ON public.faq_replies USING btree (faq_id);
CREATE INDEX ix_faq_replies_study_id ON public.faq_replies USING btree (study_id);

ALTER TABLE ONLY public.faq_replies
    ADD CONSTRAINT faq_replies_created_by_fkey FOREIGN KEY (created_by) REFERENCES public.users(id);
ALTER TABLE ONLY public.faq_replies
    ADD CONSTRAINT faq_replies_faq_id_fkey FOREIGN KEY (faq_id) REFERENCES public.faq_items(id);
ALTER TABLE ONLY public.faq_replies
    ADD CONSTRAINT faq_replies_quote_reply_id_fkey FOREIGN KEY (quote_reply_id) REFERENCES public.faq_replies(id);
ALTER TABLE ONLY public.faq_replies
    ADD CONSTRAINT faq_replies_study_id_fkey FOREIGN KEY (study_id) REFERENCES public.studies(id);

INSERT INTO public.faq_replies (id, faq_id, study_id, content, created_by, created_at)
SELECT gen_random_uuid(), id, study_id, answer, created_by, updated_at
FROM public.faq_items
WHERE answer IS NOT NULL AND btrim(answer) <> '';
