alter table public.crm_webhook_queue
  add column if not exists dead_lettered_at timestamptz,
  add column if not exists ignored_at timestamptz,
  add column if not exists ignored_by uuid references public.platform_users(id) on delete set null,
  add column if not exists last_operator_user_id uuid references public.platform_users(id) on delete set null,
  add column if not exists last_operator_action text,
  add column if not exists last_operator_note text,
  add column if not exists last_operator_at timestamptz,
  add column if not exists operator_metadata jsonb not null default '{}'::jsonb;

alter table public.crm_webhook_log
  add column if not exists queue_id uuid references public.crm_webhook_queue(id) on delete set null,
  add column if not exists operator_user_id uuid references public.platform_users(id) on delete set null,
  add column if not exists operation text;

update public.crm_webhook_queue
set dead_lettered_at = coalesce(dead_lettered_at, updated_at, created_at)
where status in ('failed', 'discarded') and dead_lettered_at is null;

create index if not exists idx_crm_queue_dead_letters
  on public.crm_webhook_queue(tenant_id, status, dead_lettered_at desc, updated_at desc)
  where status in ('failed', 'discarded');

create index if not exists idx_crm_queue_operator
  on public.crm_webhook_queue(tenant_id, last_operator_at desc)
  where last_operator_at is not null;

create index if not exists idx_crm_webhook_log_queue
  on public.crm_webhook_log(tenant_id, queue_id, created_at desc)
  where queue_id is not null;

comment on column public.crm_webhook_queue.dead_lettered_at is
  'Set when a CRM webhook task reaches a terminal failed/discarded state and needs operator review.';

comment on column public.crm_webhook_queue.ignored_at is
  'Set when a tenant operator intentionally dismisses a CRM webhook dead-letter task.';

comment on column public.crm_webhook_queue.last_operator_action is
  'Last manual CRM queue operation, for example retry or ignore.';

comment on column public.crm_webhook_log.queue_id is
  'Direct reference to the CRM queue task. Older logs may only have record_id or lead_id.';
