CREATE OR REPLACE FUNCTION public.close_resolved_collection()
RETURNS TRIGGER
LANGUAGE plpgsql
SET search_path = public
AS $$
BEGIN
  IF lower(COALESCE(NEW.status, '')) = 'resolved' THEN
    NEW.status := 'closed';
  END IF;
  RETURN NEW;
END;
$$;

DROP TRIGGER IF EXISTS close_resolved_collection_trigger ON public.collections;
CREATE TRIGGER close_resolved_collection_trigger
BEFORE INSERT OR UPDATE ON public.collections
FOR EACH ROW
EXECUTE FUNCTION public.close_resolved_collection();

CREATE OR REPLACE FUNCTION public.close_resolved_legal_matter()
RETURNS TRIGGER
LANGUAGE plpgsql
SET search_path = public
AS $$
BEGIN
  IF lower(COALESCE(NEW.current_stage, '')) = 'resolved'
     OR lower(COALESCE(NEW.status, '')) = 'resolved' THEN
    NEW.current_stage := 'resolved';
    NEW.status := 'closed';
  END IF;
  RETURN NEW;
END;
$$;

DROP TRIGGER IF EXISTS close_resolved_legal_matter_trigger ON public.legal_matters;
CREATE TRIGGER close_resolved_legal_matter_trigger
BEFORE INSERT OR UPDATE ON public.legal_matters
FOR EACH ROW
EXECUTE FUNCTION public.close_resolved_legal_matter();

UPDATE public.collections
SET status = 'closed', updated_at = now()
WHERE lower(status) = 'resolved';

UPDATE public.legal_matters
SET status = 'closed', current_stage = 'resolved', updated_at = now()
WHERE lower(status) = 'resolved' OR lower(current_stage) = 'resolved';