-- Schedule monthly cleanup for all version tables
-- Runs at 2 AM UTC on the 1st of each month
-- Keeps 50 most recent versions per entity

-- Create monitoring function
CREATE OR REPLACE FUNCTION public.log_cleanup_results()
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
  park_deleted INTEGER;
  ride_deleted INTEGER;
  company_deleted INTEGER;
  model_deleted INTEGER;
BEGIN
  -- Run cleanup and capture counts
  SELECT cleanup_old_versions('park', 50) INTO park_deleted;
  SELECT cleanup_old_versions('ride', 50) INTO ride_deleted;
  SELECT cleanup_old_versions('company', 50) INTO company_deleted;
  SELECT cleanup_old_versions('ride_model', 50) INTO model_deleted;
  
  -- Log results
  RAISE NOTICE 'Version cleanup completed: Parks=%, Rides=%, Companies=%, Models=%',
    park_deleted, ride_deleted, company_deleted, model_deleted;
END;
$$;

-- Schedule cleanup jobs
SELECT cron.schedule(
  'cleanup-all-versions',
  '0 2 1 * *',  -- 2 AM UTC on 1st of month
  $$SELECT log_cleanup_results();$$
);