/* =========================================================
   Migration: Add admin role + admin_logs table
   Run: node server/migrate-admin.js
   ========================================================= */

require("dotenv").config();
const { pool } = require("./db");

async function migrate() {
  console.log("🔄 Running admin migration...\n");

  try {
    // Add role column to users table (if not exists)
    await pool.execute(`
      ALTER TABLE users ADD COLUMN IF NOT EXISTS role VARCHAR(20) DEFAULT 'user'
    `);
    console.log("✅ Added 'role' column to users table");

    // Create admin_logs table
    await pool.execute(`
      CREATE TABLE IF NOT EXISTS admin_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        adminId VARCHAR(36) NOT NULL,
        action VARCHAR(50) NOT NULL,
        targetUserId VARCHAR(36),
        amount DECIMAL(10,3) DEFAULT 0,
        note TEXT,
        createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_admin (adminId),
        INDEX idx_target (targetUserId),
        INDEX idx_created (createdAt)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    `);
    console.log("✅ Created 'admin_logs' table");

    // Set your main account as admin (srealyza)
    await pool.execute(`
      UPDATE users SET role = 'admin' WHERE email = 'srealyza24@gmail.com'
    `);
    console.log("✅ Set srealyza24@gmail.com as admin");

    console.log("\n🎉 Migration complete!");
    process.exit(0);
  } catch (err) {
    console.error("❌ Migration failed:", err.message);
    process.exit(1);
  }
}

migrate();
