-- V002_20240110130000_create_family_structure.sql
-- Migration V002: Family Structure

-- Families table
CREATE TABLE IF NOT EXISTS families (
    id VARCHAR(20) PRIMARY KEY,
    name VARCHAR(100),
    share_code VARCHAR(10) UNIQUE,
    created_by VARCHAR(20) REFERENCES users(id),
    subscription_tier VARCHAR(20) DEFAULT 'free',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Family members table (junction table with additional data)
CREATE TABLE IF NOT EXISTS family_members (
    user_id VARCHAR(20) REFERENCES users(id) ON DELETE CASCADE,
    family_id VARCHAR(20) REFERENCES families(id) ON DELETE CASCADE,
    role VARCHAR(20) NOT NULL CHECK (role IN ('parent', 'caregiver', 'viewer')),
    permissions JSONB DEFAULT '{"canAddChildren": false, "canEditChildren": false, "canLogActivities": true, "canViewReports": true}'::jsonb,
    joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (user_id, family_id)
);

-- Children table
CREATE TABLE IF NOT EXISTS children (
    id VARCHAR(20) PRIMARY KEY,
    family_id VARCHAR(20) NOT NULL REFERENCES families(id) ON DELETE CASCADE,
    name VARCHAR(100) NOT NULL,
    birth_date DATE NOT NULL,
    gender VARCHAR(20),
    photo_url TEXT,
    medical_info JSONB DEFAULT '{}'::jsonb,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_families_share_code ON families(share_code);
CREATE INDEX IF NOT EXISTS idx_family_members_family ON family_members(family_id);
CREATE INDEX IF NOT EXISTS idx_children_family ON children(family_id);
CREATE INDEX IF NOT EXISTS idx_children_active ON children(deleted_at) WHERE deleted_at IS NULL;