CREATE OR REPLACE FUNCTION public.hard_delete_journal_entry(_entry_id uuid)
RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path = public AS $$
BEGIN
  IF _entry_id IS NULL THEN RETURN; END IF;
  DELETE FROM public.reconciliation_items WHERE journal_line_id IN (
    SELECT id FROM public.journal_lines WHERE journal_entry_id = _entry_id
  );
  DELETE FROM public.bank_transactions WHERE journal_entry_id = _entry_id;
  UPDATE public.journal_entries SET reversed_by = NULL WHERE reversed_by = _entry_id;
  UPDATE public.journal_entries SET status = 'draft', reverses_entry_id = NULL, reversed_by = NULL WHERE id = _entry_id;
  DELETE FROM public.journal_lines WHERE journal_entry_id = _entry_id;
  DELETE FROM public.journal_entries WHERE id = _entry_id;
END; $$;

REVOKE ALL ON FUNCTION public.hard_delete_journal_entry(uuid) FROM PUBLIC, anon, authenticated;