-- Migration: Setup version cleanup cron job

-- Add version retention settings to admin_settings (using proper JSONB values)
INSERT INTO public.admin_settings (setting_key, setting_value, category, description)
VALUES (
  'version_retention_days',
  '90'::jsonb,
  'maintenance',
  'Number of days to retain old version history'
)
ON CONFLICT (setting_key) DO NOTHING;

INSERT INTO public.admin_settings (setting_key, setting_value, category, description)
VALUES (
  'last_version_cleanup',
  'null'::jsonb,
  'maintenance',
  'Timestamp of last successful version cleanup'
)
ON CONFLICT (setting_key) DO NOTHING;

-- Enable pg_cron extension if not already enabled
CREATE EXTENSION IF NOT EXISTS pg_cron;

-- Unschedule existing job if it exists (to avoid duplicates)
SELECT cron.unschedule('cleanup-old-versions-weekly') WHERE EXISTS (
  SELECT 1 FROM cron.job WHERE jobname = 'cleanup-old-versions-weekly'
);

-- Schedule cleanup job: Every Sunday at 2 AM UTC
SELECT cron.schedule(
  'cleanup-old-versions-weekly',
  '0 2 * * 0',
  $$
  SELECT net.http_post(
    url := 'https://ydvtmnrszybqnbcqbdcy.supabase.co/functions/v1/cleanup-old-versions',
    headers := jsonb_build_object(
      'Content-Type', 'application/json',
      'Authorization', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4'
    ),
    body := jsonb_build_object('scheduled', true)
  ) as request_id;
  $$
);