-- V004_20240110140000_create_activity_tracking.sql
-- Migration V004: Activity Tracking Tables

-- Main activities table
CREATE TABLE IF NOT EXISTS activities (
    id VARCHAR(20) PRIMARY KEY,
    child_id VARCHAR(20) NOT NULL REFERENCES children(id) ON DELETE CASCADE,
    type VARCHAR(20) NOT NULL CHECK (type IN ('feeding', 'sleep', 'diaper', 'growth', 'medication', 'temperature', 'milestone')),
    started_at TIMESTAMP NOT NULL,
    ended_at TIMESTAMP,
    logged_by VARCHAR(20) NOT NULL REFERENCES users(id),
    notes TEXT,
    metadata JSONB DEFAULT '{}'::jsonb,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Indexes for activities
CREATE INDEX IF NOT EXISTS idx_activities_child_time ON activities(child_id, started_at DESC);
CREATE INDEX IF NOT EXISTS idx_activities_type ON activities(type, started_at DESC);
CREATE INDEX IF NOT EXISTS idx_activities_metadata ON activities USING gin(metadata);
CREATE INDEX IF NOT EXISTS idx_activities_logged_by ON activities(logged_by);

-- Index for daily summaries
CREATE INDEX IF NOT EXISTS idx_activities_daily_summary
    ON activities(child_id, type, started_at)
    WHERE ended_at IS NOT NULL;

-- Text search index for notes
CREATE INDEX IF NOT EXISTS idx_activities_notes_search
    ON activities USING gin(to_tsvector('english', COALESCE(notes, '')));