const Database = require('better-sqlite3');
const path = require('path');

const dbPath = path.join(__dirname, '../data/fitai.db');
const db = new Database(dbPath);

console.log('Creating fitness_goals table...');

try {
    db.exec(`
        CREATE TABLE IF NOT EXISTS fitness_goals (
            id TEXT PRIMARY KEY,
            user_id TEXT NOT NULL,
            fitness_profile_id TEXT,
            goal_type TEXT NOT NULL CHECK(goal_type IN ('weight_target', 'strength_milestone', 'endurance_target', 'flexibility_goal', 'habit_building', 'custom')),
            title TEXT NOT NULL,
            description TEXT,
            target_value REAL,
            current_value REAL,
            unit TEXT,
            start_date INTEGER NOT NULL,
            target_date INTEGER,
            completed_date INTEGER,
            status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'completed', 'abandoned', 'paused')),
            progress REAL DEFAULT 0,
            priority TEXT DEFAULT 'medium' CHECK(priority IN ('low', 'medium', 'high')),
            notes TEXT,
            created_at INTEGER NOT NULL,
            updated_at INTEGER NOT NULL,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            FOREIGN KEY (fitness_profile_id) REFERENCES fitness_profiles(userId) ON DELETE CASCADE
        )
    `);

    // Create indexes for better query performance
    db.exec(`
        CREATE INDEX IF NOT EXISTS idx_fitness_goals_user_id ON fitness_goals(user_id);
        CREATE INDEX IF NOT EXISTS idx_fitness_goals_status ON fitness_goals(status);
        CREATE INDEX IF NOT EXISTS idx_fitness_goals_profile_id ON fitness_goals(fitness_profile_id);
    `);

    console.log('✅ fitness_goals table created successfully');
    console.log('✅ Indexes created successfully');
} catch (error) {
    console.error('❌ Migration failed:', error);
    process.exit(1);
} finally {
    db.close();
}
