CREATE TABLE route_passport_outbox (
    id UUID PRIMARY KEY,
    route_id UUID NOT NULL,
    event_type VARCHAR(128) NOT NULL,
    topic VARCHAR(255) NOT NULL,
    message_key VARCHAR(255) NOT NULL,
    payload JSONB NOT NULL,
    headers JSONB,
    status VARCHAR(32) NOT NULL,
    attempts INTEGER NOT NULL DEFAULT 0,
    max_attempts INTEGER NOT NULL DEFAULT 10,
    next_attempt_at TIMESTAMP NOT NULL,
    locked_until TIMESTAMP,
    last_error TEXT,
    created_at TIMESTAMP NOT NULL,
    updated_at TIMESTAMP NOT NULL,
    published_at TIMESTAMP,

    CONSTRAINT fk_route_passport_outbox_route
        FOREIGN KEY (route_id)
        REFERENCES route_passports (route_id)
        ON DELETE CASCADE,

    CONSTRAINT ux_route_passport_outbox_route_event
        UNIQUE (route_id, event_type),

    CONSTRAINT chk_route_passport_outbox_status
        CHECK (status IN ('PENDING', 'PUBLISHED', 'FAILED'))
);

CREATE INDEX idx_route_passport_outbox_due
    ON route_passport_outbox (status, next_attempt_at, created_at);

CREATE INDEX idx_route_passport_outbox_locked_until
    ON route_passport_outbox (locked_until);

CREATE INDEX idx_route_passport_outbox_route_id
    ON route_passport_outbox (route_id);
