-- Migration: Add Predefined Task Support to scheduled_jobs
-- Date: 2025-12-11
-- Purpose: Transition from dynamic code execution to predefined task system

-- 1. Create job_type ENUM type
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'jobtype') THEN
        CREATE TYPE jobtype AS ENUM ('predefined', 'custom_code');
    END IF;
END $$;

-- 2. Add new columns
ALTER TABLE scheduled_jobs
ADD COLUMN IF NOT EXISTS job_type jobtype DEFAULT 'custom_code',
ADD COLUMN IF NOT EXISTS predefined_function VARCHAR(100),
ADD COLUMN IF NOT EXISTS function_params JSONB DEFAULT '{}'::jsonb;

-- 3. Update existing rows to custom_code type (preserve backward compatibility)
UPDATE scheduled_jobs
SET job_type = 'custom_code'
WHERE job_type IS NULL;

-- 4. Make job_type NOT NULL after setting defaults
ALTER TABLE scheduled_jobs
ALTER COLUMN job_type SET NOT NULL;

-- 5. Set default for job_type to 'predefined' for new records
ALTER TABLE scheduled_jobs
ALTER COLUMN job_type SET DEFAULT 'predefined';

-- 6. Add check constraint
ALTER TABLE scheduled_jobs
ADD CONSTRAINT chk_job_type_fields
CHECK (
    (job_type = 'predefined' AND predefined_function IS NOT NULL)
    OR
    (job_type = 'custom_code' AND python_code IS NOT NULL)
);

-- 7. Add comment on columns
COMMENT ON COLUMN scheduled_jobs.job_type IS 'Job type: predefined or custom_code';
COMMENT ON COLUMN scheduled_jobs.predefined_function IS 'Predefined function name (required if job_type=predefined)';
COMMENT ON COLUMN scheduled_jobs.function_params IS 'JSON parameters for predefined function';
COMMENT ON COLUMN scheduled_jobs.python_code IS 'Dynamic Python code (only for custom_code type)';

-- 8. Verify the changes
SELECT
    column_name,
    data_type,
    is_nullable,
    column_default
FROM information_schema.columns
WHERE table_name = 'scheduled_jobs'
ORDER BY ordinal_position;
