-- Migration 016: Fix job_type/job_status enums and add jobs TTL (#75, #70)
--
-- 1. Add 'proxy' and 'import' to job_type so queue names match enum values.
-- 2. Add 'completed' to job_status to match the trimWorker status string.
-- 3. Add expires_at column to jobs so stale trim rows auto-expire (#70).

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_enum
    WHERE enumlabel = 'proxy' AND enumtypid = 'job_type'::regtype
  ) THEN
    ALTER TYPE job_type ADD VALUE 'proxy';
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM pg_enum
    WHERE enumlabel = 'import' AND enumtypid = 'job_type'::regtype
  ) THEN
    ALTER TYPE job_type ADD VALUE 'import';
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM pg_enum
    WHERE enumlabel = 'completed' AND enumtypid = 'job_status'::regtype
  ) THEN
    ALTER TYPE job_status ADD VALUE 'completed';
  END IF;
END $$;

-- Add TTL column to jobs (NULL = no expiry; trim jobs set 24h from creation)
ALTER TABLE jobs
  ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ DEFAULT NULL;

-- Backfill: give any existing trim rows a 24h TTL from their creation time
UPDATE jobs SET expires_at = created_at + INTERVAL '24 hours'
  WHERE type = 'trim' AND expires_at IS NULL;
