create table if not exists user_ai_permissions (
  user_id uuid not null references users(id) on delete cascade,
  scope_code text not null,
  access_level text not null default 'denied' check (access_level in ('denied', 'read', 'operate')),
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  primary key (user_id, scope_code)
);

create index if not exists idx_user_ai_permissions_scope
  on user_ai_permissions(scope_code, access_level);

create table if not exists ai_assist_audit_logs (
  id uuid primary key default gen_random_uuid(),
  user_id uuid references users(id) on delete set null,
  intent text not null default '',
  requested_scope text not null default '',
  decision text not null check (decision in ('allowed', 'denied', 'blocked')),
  risk_code text not null default '',
  action_type text not null default '',
  metadata jsonb not null default '{}'::jsonb,
  created_at timestamptz not null default now()
);

create index if not exists idx_ai_assist_audit_logs_user_time
  on ai_assist_audit_logs(user_id, created_at desc);

create index if not exists idx_ai_assist_audit_logs_scope_time
  on ai_assist_audit_logs(requested_scope, decision, created_at desc);
