-- Migration V017: Add child display preferences
-- Created: 2025-10-04
-- Description: Adds display_color, sort_order, and nickname fields for multi-child UI support

-- Add display preferences columns to children table
ALTER TABLE children
ADD COLUMN display_color VARCHAR(7) DEFAULT '#FF6B9D',
ADD COLUMN sort_order INTEGER DEFAULT 0,
ADD COLUMN nickname VARCHAR(50);

-- Update existing children with colors based on creation order within each family
WITH numbered_children AS (
  SELECT
    id,
    family_id,
    ROW_NUMBER() OVER (PARTITION BY family_id ORDER BY created_at) - 1 AS row_num
  FROM children
  WHERE deleted_at IS NULL
)
UPDATE children c
SET
  display_color = CASE (nc.row_num % 8)
    WHEN 0 THEN '#FF6B9D'  -- Pink
    WHEN 1 THEN '#4ECDC4'  -- Teal
    WHEN 2 THEN '#FFD93D'  -- Yellow
    WHEN 3 THEN '#95E1D3'  -- Mint
    WHEN 4 THEN '#C7CEEA'  -- Lavender
    WHEN 5 THEN '#FF8C42'  -- Orange
    WHEN 6 THEN '#A8E6CF'  -- Green
    WHEN 7 THEN '#B8B8FF'  -- Purple
  END,
  sort_order = nc.row_num
FROM numbered_children nc
WHERE c.id = nc.id;

-- Create composite index for efficient family queries with sorting
CREATE INDEX IF NOT EXISTS idx_children_family_sort
ON children(family_id, sort_order, deleted_at);

-- Add comments for documentation
COMMENT ON COLUMN children.display_color IS 'Hex color code for consistent UI display across charts and cards';
COMMENT ON COLUMN children.sort_order IS 'Display order within family (0-based, typically by birth order)';
COMMENT ON COLUMN children.nickname IS 'Optional shortened name for voice commands and quick selection';
