-- Migration: Add group_name field to wishlist_items and tasks tables
-- Date: 2026-02-XX
--
-- This migration:
-- 1. Adds group_name field to wishlist_items (replacing project_id)
-- 2. Migrates existing data from project_id to group_name
-- 3. Removes project_id column from wishlist_items
-- 4. Adds group_name field to tasks
-- 5. Creates materialized view for group suggestions

-- Step 1: Add group_name to wishlist_items
ALTER TABLE wishlist_items 
ADD COLUMN group_name VARCHAR(255);

-- Step 2: Migrate existing data from project_id to group_name
UPDATE wishlist_items wi
SET group_name = p.name
FROM projects p
WHERE wi.project_id = p.id AND wi.project_id IS NOT NULL;

-- Step 3: Remove project_id column and its index
DROP INDEX IF EXISTS idx_wishlist_items_project_id;
ALTER TABLE wishlist_items 
DROP COLUMN project_id;

-- Step 4: Add group_name to tasks
ALTER TABLE tasks 
ADD COLUMN group_name VARCHAR(255);

-- Step 5: Create indexes on group_name
CREATE INDEX idx_wishlist_items_group_name ON wishlist_items(group_name) WHERE group_name IS NOT NULL;
CREATE INDEX idx_tasks_group_name ON tasks(group_name) WHERE group_name IS NOT NULL;

-- Step 6: Create materialized view for group suggestions
CREATE MATERIALIZED VIEW user_group_suggestions_mv AS
SELECT DISTINCT user_id, group_name FROM (
    -- Желания пользователя (собственные)
    SELECT wi.user_id, wi.group_name FROM wishlist_items wi
    WHERE wi.deleted = FALSE AND wi.group_name IS NOT NULL AND wi.group_name != ''
    UNION
    -- Желания с досок, на которых пользователь участник
    SELECT wbm.user_id, wi.group_name FROM wishlist_items wi
    JOIN wishlist_board_members wbm ON wi.board_id = wbm.board_id
    WHERE wi.deleted = FALSE AND wi.group_name IS NOT NULL AND wi.group_name != ''
    UNION
    -- Задачи пользователя
    SELECT t.user_id, t.group_name FROM tasks t
    WHERE t.deleted = FALSE AND t.group_name IS NOT NULL AND t.group_name != ''
    UNION
    -- Имена проектов пользователя
    SELECT p.user_id, p.name FROM projects p
    WHERE p.deleted = FALSE
) sub;

-- Step 7: Create unique index for CONCURRENT refresh
CREATE UNIQUE INDEX idx_user_group_suggestions_mv_user_group ON user_group_suggestions_mv(user_id, group_name);

COMMENT ON COLUMN wishlist_items.group_name IS 'Group name for wishlist item (free text, replaces project_id)';
COMMENT ON COLUMN tasks.group_name IS 'Group name for task (free text)';
COMMENT ON MATERIALIZED VIEW user_group_suggestions_mv IS 'Materialized view for group name suggestions per user';
