-- 1. Create themes table
CREATE TABLE themes (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    name TEXT NOT NULL,
    theme TEXT NOT NULL,
    categories JSONB NOT NULL DEFAULT '[]',
    max_items_per_category INTEGER NOT NULL DEFAULT 4,
    max_age_days INTEGER NOT NULL DEFAULT 7,
    summary_length INTEGER NOT NULL DEFAULT 3,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_themes_user_id ON themes(user_id);

-- 2. Migrate existing settings to default themes
INSERT INTO themes (user_id, name, theme, categories, max_items_per_category, max_age_days, summary_length)
SELECT user_id, theme, theme, categories, max_items_per_category, max_age_days, summary_length
FROM settings;

-- 3. Add theme_id to sources (nullable)
ALTER TABLE sources ADD COLUMN theme_id UUID REFERENCES themes(id) ON DELETE CASCADE;

-- 4. Backfill sources with the user's default theme
UPDATE sources s
SET theme_id = t.id
FROM themes t
WHERE s.user_id = t.user_id;

-- 5. Add theme_id to syntheses (nullable, SET NULL on theme deletion)
ALTER TABLE syntheses ADD COLUMN theme_id UUID REFERENCES themes(id) ON DELETE SET NULL;

-- 6. Backfill syntheses with the user's default theme
UPDATE syntheses sy
SET theme_id = t.id
FROM themes t
WHERE sy.user_id = t.user_id;

-- 7. Drop moved columns from settings
ALTER TABLE settings DROP COLUMN theme;
ALTER TABLE settings DROP COLUMN categories;
ALTER TABLE settings DROP COLUMN max_items_per_category;
ALTER TABLE settings DROP COLUMN max_age_days;
ALTER TABLE settings DROP COLUMN summary_length;
