ALTER TABLE outbox
    DROP CONSTRAINT IF EXISTS outbox_status_valid_chk;

ALTER TABLE outbox
    ADD CONSTRAINT outbox_status_valid_chk
    CHECK (status IN ('draft', 'queued', 'scheduled', 'sending', 'sent', 'failed', 'cancelled')) NOT VALID;

CREATE TABLE IF NOT EXISTS outbox_dead_letters (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    outbox_id UUID NOT NULL REFERENCES outbox(id) ON DELETE CASCADE,
    attempt_count INT NOT NULL DEFAULT 0,
    error TEXT NOT NULL DEFAULT '',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_outbox_dead_letters_outbox
    ON outbox_dead_letters(outbox_id, created_at DESC);
