-- Emails
CREATE TABLE IF NOT EXISTS public.emails (
    id_email integer NOT NULL,
    user_id UUID NOT NULL,
    created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT now() NOT NULL,
    DATA json NOT NULL
);
-- Primary Key
DO $$ BEGIN
ALTER TABLE public.emails 
ADD CONSTRAINT emails_pkey PRIMARY KEY (id_email);
    EXCEPTION
        WHEN invalid_table_definition THEN
            RAISE NOTICE 'Primary key already exists. Ignoring...'; 
END $$;
-- Sequence for id_email
DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_sequences 
    WHERE schemaname = 'public' AND sequencename = 'emails_id_email_seq'
    ) THEN
        CREATE SEQUENCE public.emails_id_email_seq 
        AS integer 
        START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1;
    END IF;
END $$;

ALTER SEQUENCE public.emails_id_email_seq OWNED BY public.emails.id_email;

-- Set default for id_email
ALTER TABLE public.emails
ALTER COLUMN id_email
SET DEFAULT nextval(
    'public.emails_id_email_seq'::regclass
);
-- Foreign Key to Users
DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'email_user'
    ) THEN
        ALTER TABLE public.emails 
        ADD CONSTRAINT email_user 
        FOREIGN KEY (user_id) REFERENCES public.users (id) 
        ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $$;