create schema if not exists kbx;

create table if not exists kbx.ux_events (
  id uuid primary key,
  tenant_id uuid not null,
  event_name varchar(80) not null,
  screen_id varchar(80),
  screen_version varchar(20),
  session_id uuid not null,
  task_session_id uuid,
  app_version varchar(40),
  occurred_at timestamptz not null,
  received_at timestamptz not null default now(),
  duration_ms integer,
  event_count integer not null default 1 check(event_count > 0),
  attributes jsonb not null default '{}'::jsonb,
  check(duration_ms is null or duration_ms between 0 and 86400000)
);
create index if not exists ix_ux_events_tenant_time on kbx.ux_events(tenant_id,occurred_at desc);
create index if not exists ix_ux_events_tenant_event_time on kbx.ux_events(tenant_id,event_name,occurred_at desc);
create index if not exists ix_ux_events_screen_time on kbx.ux_events(tenant_id,screen_id,occurred_at desc) where screen_id is not null;

-- Server-side business outcome counters are intentionally separate from browser interaction events.
-- No order/customer/item identity is stored; only low-cardinality work type and counts.
create table if not exists kbx.ux_business_outcomes (
  tenant_id uuid not null,
  business_date date not null,
  screen_id varchar(80) not null default '',
  work_type varchar(80) not null,
  reason_code varchar(80) not null default '',
  observed_count integer not null check(observed_count >= 0),
  auto_processed_count integer not null check(auto_processed_count >= 0),
  manual_intervention_count integer not null check(manual_intervention_count >= 0),
  updated_at timestamptz not null default now(),
  primary key(tenant_id,business_date,screen_id,work_type,reason_code),
  check(auto_processed_count + manual_intervention_count <= observed_count)
);

comment on table kbx.ux_events is 'KBX semantic UX telemetry. Raw business values and sensitive data are prohibited.';
comment on table kbx.ux_business_outcomes is 'Aggregated business workload counts used for Manual Intervention Rate; no business entity identifiers.';
