-- Migration V019: Add bulk operation tracking for activities
-- Created: 2025-10-04
-- Description: Adds columns to track activities logged simultaneously for multiple children

-- Add bulk operation tracking columns to activities table
ALTER TABLE activities
ADD COLUMN bulk_operation_id UUID,
ADD COLUMN siblings_count INTEGER DEFAULT 1;

-- Create index for bulk operation queries
CREATE INDEX IF NOT EXISTS idx_activities_bulk_operation
ON activities(bulk_operation_id)
WHERE bulk_operation_id IS NOT NULL;

-- Add foreign key constraint for child_id if not already exists
-- This ensures all activities are linked to valid children
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM information_schema.table_constraints
    WHERE constraint_name = 'fk_activities_child'
    AND table_name = 'activities'
  ) THEN
    ALTER TABLE activities
    ADD CONSTRAINT fk_activities_child
    FOREIGN KEY (child_id)
    REFERENCES children(id)
    ON DELETE CASCADE;
  END IF;
END $$;

-- Optimize index for multi-child queries (child_id, type, started_at)
-- Note: activities table uses started_at instead of timestamp
CREATE INDEX IF NOT EXISTS idx_activities_multi_child_query
ON activities(child_id, type, started_at DESC);

-- Create composite index for efficient filtering by multiple children
-- This supports queries like: WHERE child_id IN ('id1', 'id2', 'id3')
CREATE INDEX IF NOT EXISTS idx_activities_child_started_at
ON activities(child_id, started_at DESC);

-- Add comments for documentation
COMMENT ON COLUMN activities.bulk_operation_id IS 'UUID linking activities logged simultaneously for multiple children';
COMMENT ON COLUMN activities.siblings_count IS 'Total number of children this activity was logged for (for UI context)';
