-- Migration: Refactor configs to link via tasks.config_id
-- This migration adds config_id to tasks table and migrates existing configs to tasks
-- After migration: configs only contain words_count, max_cards (name and try_message removed)

-- ============================================
-- Step 1: Add config_id to tasks
-- ============================================
ALTER TABLE tasks 
ADD COLUMN IF NOT EXISTS config_id INTEGER REFERENCES configs(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_tasks_config_id ON tasks(config_id);

-- Unique index: only one task per config
CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_config_id_unique 
ON tasks(config_id) WHERE config_id IS NOT NULL AND deleted = FALSE;

COMMENT ON COLUMN tasks.config_id IS 'Link to test config. NULL if task is not a test.';

-- ============================================
-- Step 2: Migrate existing configs to tasks
-- Create a task for each config that doesn't have one yet
-- ============================================
INSERT INTO tasks (user_id, name, reward_message, repetition_period, repetition_date, config_id)
SELECT 
    c.user_id,
    c.name,                    -- Config name -> Task name
    c.try_message,             -- try_message -> reward_message
    '0 day'::INTERVAL,         -- repetition_period = 0 (infinite task)
    '0 week',                  -- repetition_date = 0 (infinite task)
    c.id                       -- Link to config
FROM configs c
WHERE c.name IS NOT NULL       -- Only configs with names
AND NOT EXISTS (
    SELECT 1 FROM tasks t WHERE t.config_id = c.id AND t.deleted = FALSE
);

-- ============================================
-- Step 3: Remove name and try_message from configs
-- These are now stored in the linked task
-- ============================================
ALTER TABLE configs DROP COLUMN IF EXISTS name;
ALTER TABLE configs DROP COLUMN IF EXISTS try_message;

-- ============================================
-- Comments for documentation
-- ============================================
COMMENT ON TABLE configs IS 'Test configurations (words_count, max_cards, dictionary associations). Linked to tasks via tasks.config_id.';


