import sqlite3 from 'sqlite3';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const dbPath = path.join(__dirname, 'database.sqlite');
const db = new sqlite3.Database(dbPath);

console.log('🔄 Starting database migration...');

// Promisify database operations
function dbRun(sql, params = []) {
  return new Promise((resolve, reject) => {
    db.run(sql, params, function(err) {
      if (err) reject(err);
      else resolve({ lastID: this.lastID, changes: this.changes });
    });
  });
}

function dbAll(sql, params = []) {
  return new Promise((resolve, reject) => {
    db.all(sql, params, (err, rows) => {
      if (err) reject(err);
      else resolve(rows);
    });
  });
}

async function migrate() {
  try {
    // Check if old medicines table exists
    const tables = await dbAll(`
      SELECT name FROM sqlite_master 
      WHERE type='table' AND name='medicines'
    `);

    if (tables.length > 0) {
      console.log('📋 Found old medicines table');
      
      // Check if we need to migrate pharmacy_medicines
      const columns = await dbAll(`PRAGMA table_info(pharmacy_medicines)`);
      const hasMedicineId = columns.some(col => col.name === 'medicine_id');
      const hasNregistro = columns.some(col => col.name === 'medicine_nregistro');

      if (hasMedicineId && !hasNregistro) {
        console.log('🔄 Migrating pharmacy_medicines table...');
        
        // Create new table with updated schema
        await dbRun(`
          CREATE TABLE pharmacy_medicines_new (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            pharmacy_id INTEGER NOT NULL,
            medicine_nregistro TEXT NOT NULL,
            medicine_name TEXT,
            price REAL,
            stock INTEGER DEFAULT 0,
            FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
            UNIQUE(pharmacy_id, medicine_nregistro)
          )
        `);

        console.log('✅ Created new pharmacy_medicines table');
        
        // Copy data if any exists (though it will be invalid without nregistro)
        const oldData = await dbAll('SELECT * FROM pharmacy_medicines');
        console.log(`📦 Found ${oldData.length} old pharmacy-medicine relationships`);
        
        if (oldData.length > 0) {
          console.log('⚠️  Warning: Old medicine relationships will be lost.');
          console.log('   You will need to re-link medicines using the CIMA database.');
        }
        
        // Drop old table
        await dbRun('DROP TABLE pharmacy_medicines');
        
        // Rename new table
        await dbRun('ALTER TABLE pharmacy_medicines_new RENAME TO pharmacy_medicines');
        
        console.log('✅ Migrated pharmacy_medicines table');
      } else if (hasNregistro) {
        console.log('✅ pharmacy_medicines table already migrated');
      }

      // We can keep the old medicines table for reference, or drop it
      console.log('ℹ️  Old medicines table can be kept for reference or deleted manually');
      console.log('   To delete: sqlite3 database.sqlite "DROP TABLE IF EXISTS medicines;"');
    } else {
      console.log('✅ No old medicines table found - creating new schema');
      
      // Create pharmacy_medicines table with new schema
      await dbRun(`
        CREATE TABLE IF NOT EXISTS pharmacy_medicines (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          pharmacy_id INTEGER NOT NULL,
          medicine_nregistro TEXT NOT NULL,
          medicine_name TEXT,
          price REAL,
          stock INTEGER DEFAULT 0,
          FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
          UNIQUE(pharmacy_id, medicine_nregistro)
        )
      `);
      
      console.log('✅ Created pharmacy_medicines table');
    }

    console.log('');
    console.log('✨ Migration completed successfully!');
    console.log('');
    console.log('Next steps:');
    console.log('1. Install Redis: brew install redis (macOS) or apt-get install redis-server (Linux)');
    console.log('2. Start Redis: redis-server');
    console.log('3. Install dependencies: npm install');
    console.log('4. Start the server: npm start');
    
  } catch (error) {
    console.error('❌ Migration failed:', error);
    process.exit(1);
  } finally {
    db.close();
  }
}

migrate();
