-- Migration 009: Sleep Log Table
-- v9d Phase 2b: Sleep Module Core
-- Date: 2026-03-22

CREATE TABLE IF NOT EXISTS sleep_log (
    id SERIAL PRIMARY KEY,
    profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
    date DATE NOT NULL,
    bedtime TIME,
    wake_time TIME,
    duration_minutes INTEGER NOT NULL CHECK (duration_minutes > 0),
    quality INTEGER CHECK (quality >= 1 AND quality <= 5),
    wake_count INTEGER CHECK (wake_count >= 0),
    deep_minutes INTEGER CHECK (deep_minutes >= 0),
    rem_minutes INTEGER CHECK (rem_minutes >= 0),
    light_minutes INTEGER CHECK (light_minutes >= 0),
    awake_minutes INTEGER CHECK (awake_minutes >= 0),
    sleep_segments JSONB,
    note TEXT,
    source VARCHAR(20) DEFAULT 'manual' CHECK (source IN ('manual', 'apple_health', 'garmin')),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT unique_sleep_per_day UNIQUE(profile_id, date)
);

CREATE INDEX idx_sleep_profile_date ON sleep_log(profile_id, date DESC);

-- Comments for documentation
COMMENT ON TABLE sleep_log IS 'v9d Phase 2b: Daily sleep tracking with phase data';
COMMENT ON COLUMN sleep_log.date IS 'Date of the night (wake date, not bedtime date)';
COMMENT ON COLUMN sleep_log.sleep_segments IS 'Raw phase segments: [{"phase": "deep", "start": "23:44", "duration_min": 42}, ...]';
