-- Migration: Remove group_name field from wishlist_items and tasks tables
-- Date: 2026-02-XX
--
-- This migration reverses the changes made in 000014_add_group_name.up.sql

-- Step 1: Drop materialized view
DROP MATERIALIZED VIEW IF EXISTS user_group_suggestions_mv;

-- Step 2: Drop indexes on group_name
DROP INDEX IF EXISTS idx_tasks_group_name;
DROP INDEX IF EXISTS idx_wishlist_items_group_name;

-- Step 3: Remove group_name from tasks
ALTER TABLE tasks 
DROP COLUMN group_name;

-- Step 4: Add back project_id to wishlist_items
ALTER TABLE wishlist_items 
ADD COLUMN project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL;

-- Step 5: Try to restore project_id from group_name (if possible)
-- Note: This is best-effort, as group_name might not match project names exactly
UPDATE wishlist_items wi
SET project_id = p.id
FROM projects p
WHERE wi.group_name = p.name 
  AND wi.group_name IS NOT NULL 
  AND wi.group_name != ''
  AND p.deleted = FALSE;

-- Step 6: Create index on project_id
CREATE INDEX idx_wishlist_items_project_id ON wishlist_items(project_id);

-- Step 7: Remove group_name from wishlist_items
ALTER TABLE wishlist_items 
DROP COLUMN group_name;
