CREATE TABLE IF NOT EXISTS mail_queue (
    id           SERIAL PRIMARY KEY,
    to_email     TEXT    NOT NULL,
    subject      TEXT    NOT NULL,
    body         TEXT    NOT NULL,
    status       TEXT    NOT NULL DEFAULT 'pending',
    attempts     INTEGER NOT NULL DEFAULT 0,
    available_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
    locked_at    TIMESTAMP WITH TIME ZONE,
    last_error   TEXT,
    created_at   TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_mail_queue_pending
    ON mail_queue (available_at ASC, id ASC)
    WHERE status = 'pending';
