begin;

-- C/D (and other no-evidence choice answers) must update the latest result's
-- inference_state in place. The candidate persist RPC caches on the evidence
-- fingerprint, so a receipt-only posterior write cannot go through that path
-- without waiting for the next dated-event rescore.

create or replace function public.patch_agentic_rectification_inference_state(
  p_user_id uuid,
  p_case_id uuid,
  p_inference_state jsonb
)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
  v_case public.agentic_rectification_cases%rowtype;
  v_result public.agentic_rectification_results%rowtype;
  v_receipt jsonb;
begin
  if p_user_id is null or p_case_id is null
    or p_inference_state is null
    or jsonb_typeof(p_inference_state) <> 'object' then
    raise exception 'agentic_rectification_invalid_input' using errcode = 'P0001';
  end if;

  select * into v_case
  from public.agentic_rectification_cases
  where id = p_case_id and user_id = p_user_id
  for update;
  if not found then
    raise exception 'agentic_rectification_case_not_found' using errcode = 'P0001';
  end if;
  if v_case.status in ('confirmed', 'closed', 'abandoned', 'superseded') then
    raise exception 'agentic_rectification_case_terminal' using errcode = 'P0001';
  end if;

  select * into v_result
  from public.agentic_rectification_results
  where case_id = p_case_id
    and invalidated_at is null
  order by created_at desc
  limit 1
  for update;
  if not found then
    raise exception 'agentic_rectification_result_not_found' using errcode = 'P0001';
  end if;
  if v_result.decision_receipt is null
    or jsonb_typeof(v_result.decision_receipt) <> 'object' then
    raise exception 'agentic_rectification_invalid_decision_receipt' using errcode = 'P0001';
  end if;

  v_receipt := jsonb_set(v_result.decision_receipt, '{inference_state}', p_inference_state, true);

  update public.agentic_rectification_results
  set decision_receipt = v_receipt
  where id = v_result.id;

  return jsonb_build_object(
    'result_id', v_result.id,
    'decision_receipt', v_receipt
  );
end;
$$;

revoke all on function public.patch_agentic_rectification_inference_state(uuid, uuid, jsonb)
  from public, anon, authenticated;
grant execute on function public.patch_agentic_rectification_inference_state(uuid, uuid, jsonb)
  to service_role;

commit;
