create schema if not exists kbx;

create table if not exists kbx.integration_attempts (
    id uuid primary key,
    tenant_id uuid not null,
    integration_id text not null,
    message_id uuid not null,
    aggregate_type text not null,
    aggregate_id text not null,
    aggregate_version bigint null,
    attempt_no integer not null check (attempt_no > 0),
    state text not null check (state in ('queued','delivering','retrying','delivered','failed','suspended')),
    failure_kind text null check (failure_kind in ('transient','permanent')),
    failure_code text null,
    detail text null,
    http_status integer null,
    external_reference text null,
    correlation_id text not null,
    manual_retry_key text null,
    started_at timestamptz not null,
    completed_at timestamptz null,
    next_retry_at timestamptz null,
    unique (tenant_id, integration_id, message_id, attempt_no)
);
create index if not exists ix_integration_attempts_retry on kbx.integration_attempts(tenant_id,state,next_retry_at) where state='retrying';
create index if not exists ix_integration_attempts_aggregate on kbx.integration_attempts(tenant_id,aggregate_type,aggregate_id,started_at desc);
create unique index if not exists ux_integration_manual_retry on kbx.integration_attempts(tenant_id,manual_retry_key) where manual_retry_key is not null;

create table if not exists kbx.integration_receipts (
    tenant_id uuid not null,
    integration_id text not null,
    message_key text not null,
    received_at timestamptz not null,
    processed_at timestamptz null,
    result jsonb null,
    primary key (tenant_id,integration_id,message_key)
);
