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

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

function migrateRoles() {
    try {
        console.log('Starting migration to update role constraints...');

        // 1. Disable foreign keys
        db.pragma('foreign_keys = OFF');

        // 2. Start transaction
        db.transaction(() => {
            // 3. Create new table with updated check constraint
            console.log('Creating new users table...');
            db.prepare(`
        CREATE TABLE IF NOT EXISTS users_new (
            id TEXT PRIMARY KEY,
            email TEXT UNIQUE NOT NULL,
            firstName TEXT NOT NULL,
            lastName TEXT NOT NULL,
            password TEXT NOT NULL,
            phone TEXT,
            role TEXT NOT NULL CHECK (role IN ('superAdmin', 'admin', 'trainer', 'client')),
            createdAt DATETIME NOT NULL,
            updatedAt DATETIME NOT NULL
        )
      `).run();

            // 4. Copy data
            console.log('Copying data...');
            db.prepare(`
        INSERT INTO users_new (id, email, firstName, lastName, password, phone, role, createdAt, updatedAt)
        SELECT id, email, firstName, lastName, password, phone, role, createdAt, updatedAt FROM users
      `).run();

            // 5. Drop old table
            console.log('Dropping old table...');
            db.prepare('DROP TABLE users').run();

            // 6. Rename new table
            console.log('Renaming new table...');
            db.prepare('ALTER TABLE users_new RENAME TO users').run();

            // 7. Re-enable foreign keys (in a separate step usually, but good to be safe)
        })();

        db.pragma('foreign_keys = ON');

        console.log('Migration completed successfully.');

    } catch (error) {
        console.error('Migration failed:', error);
        process.exit(1);
    } finally {
        db.close();
    }
}

migrateRoles();
