-- DROP TABLE IF EXISTS public.queue_type CASCADE;
CREATE TABLE public.queue_type (
    id                  BIGSERIAL PRIMARY KEY,
    value               TEXT NOT NULL UNIQUE,
    created_ts          TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_ts          TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx__public__queue_type__value          ON public.queue_type (value);
CREATE INDEX idx__public__queue_type__created_ts     ON public.queue_type (created_ts);
CREATE INDEX idx__public__queue_type__updated_ts     ON public.queue_type (updated_ts);

INSERT INTO public.queue_type (value) VALUES ('audit') ON CONFLICT DO NOTHING;

-- DROP TABLE IF EXISTS public.queue_url CASCADE;
CREATE TABLE public.queue_url (
    id                  BIGSERIAL PRIMARY KEY,
    value               TEXT NOT NULL UNIQUE,
    next_run_ts         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    created_ts          TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_ts          TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx__public__queue_url__value          ON public.queue_url (value);
CREATE INDEX idx__public__queue_url__next_run_ts    ON public.queue_url (next_run_ts);
CREATE INDEX idx__public__queue_url__created_ts     ON public.queue_url (created_ts);
CREATE INDEX idx__public__queue_url__updated_ts     ON public.queue_url (updated_ts);


-- DROP TABLE IF EXISTS public.queue CASCADE;
CREATE TABLE public.queue (
    id                  BIGSERIAL PRIMARY KEY,
    queue_type_id       BIGINT NOT NULL REFERENCES public.queue_type(id),
    queue_url_id        BIGINT NOT NULL REFERENCES public.queue_url(id),
    headers             JSON,
    data                JSON,
    run_count           BIGINT NOT NULL DEFAULT 0,
    last_fail           TEXT,
    last_run_ts         TIMESTAMPTZ,
    created_ts          TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_ts          TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx__public__queue__queue_type_id  ON public.queue (queue_type_id);
CREATE INDEX idx__public__queue__run_count      ON public.queue (run_count);
CREATE INDEX idx__public__queue__last_run_ts    ON public.queue (last_run_ts);
CREATE INDEX idx__public__queue__created_ts     ON public.queue (created_ts);
CREATE INDEX idx__public__queue__updated_ts     ON public.queue (updated_ts);
