-- =====================================================
-- Automatic Cleanup of Temporary References
-- =====================================================
-- Trigger to delete submission_item_temp_refs when items are approved
-- This acts as a safety net if edge function cleanup fails

-- Function to cleanup temp refs on approval
CREATE OR REPLACE FUNCTION public.cleanup_temp_refs_on_approval()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
  v_deleted_count INTEGER;
BEGIN
  -- Only cleanup when status changes to approved
  IF NEW.status = 'approved' AND OLD.status != 'approved' THEN
    -- Delete all temp refs for this submission item
    DELETE FROM public.submission_item_temp_refs
    WHERE submission_item_id = NEW.id;
    
    GET DIAGNOSTICS v_deleted_count = ROW_COUNT;
    
    IF v_deleted_count > 0 THEN
      RAISE NOTICE 'Cleaned up % temp refs for submission_item %', v_deleted_count, NEW.id;
    END IF;
  END IF;
  
  RETURN NEW;
EXCEPTION WHEN OTHERS THEN
  -- Log but don't block the approval
  RAISE NOTICE 'Failed to cleanup temp refs for item %: %', NEW.id, SQLERRM;
  RETURN NEW;
END;
$function$;

-- Create trigger on submission_items
CREATE TRIGGER trigger_cleanup_temp_refs_on_approval
  AFTER UPDATE OF status ON public.submission_items
  FOR EACH ROW
  WHEN (NEW.status = 'approved' AND OLD.status IS DISTINCT FROM 'approved')
  EXECUTE FUNCTION public.cleanup_temp_refs_on_approval();

COMMENT ON FUNCTION public.cleanup_temp_refs_on_approval() IS 
  'Automatically deletes temporary reference records when submission items are approved. Acts as safety net for edge function cleanup.';

COMMENT ON TRIGGER trigger_cleanup_temp_refs_on_approval ON public.submission_items IS
  'Ensures temp refs are cleaned up even if edge function cleanup fails';