-- A 422 from GPT is a terminal reading result for this exact file revision.
-- Keep it visible as failed instead of retrying forever or leaving it pending.
create or replace function public.fail_workspace_permit(
  p_permit_id uuid, p_lease uuid, p_revision bigint, p_error text
) returns boolean language plpgsql security definer set search_path = public as $$
begin
  if p_error not in ('not_a_permit', 'unreadable_file', 'no_state_detected') then
    raise exception 'Unsupported terminal permit code';
  end if;
  perform 1 from public.permits where id=p_permit_id for update;
  if not found then return false; end if;
  perform 1 from public.permit_processing_jobs where permit_id=p_permit_id
    and lease_token=p_lease and revision=p_revision and status='processing' for update;
  if not found then return false; end if;
  update public.permits set extraction_status='failed', route_processing_status='failed'
    where id=p_permit_id;
  update public.permit_processing_jobs set status='done', last_error=p_error,
    lease_token=null, lease_until=null, updated_at=now() where permit_id=p_permit_id;
  return true;
end $$;

revoke all on function public.fail_workspace_permit(uuid,uuid,bigint,text) from public, anon, authenticated;
grant execute on function public.fail_workspace_permit(uuid,uuid,bigint,text) to service_role;
