import { pool } from "./config/db.js";

async function migrate() {
  console.log("Starting users table migration...");
  try {
    // Check if columns already exist to avoid errors
    const [columns] = await pool.query("SHOW COLUMNS FROM users");
    const fieldNames = columns.map(c => c.Field);

    if (!fieldNames.includes("full_name")) {
      await pool.query("ALTER TABLE users ADD COLUMN full_name VARCHAR(100) DEFAULT NULL");
      console.log("Added full_name column.");
    }
    if (!fieldNames.includes("email")) {
      await pool.query("ALTER TABLE users ADD COLUMN email VARCHAR(100) DEFAULT NULL");
      console.log("Added email column.");
    }
    if (!fieldNames.includes("phone")) {
      await pool.query("ALTER TABLE users ADD COLUMN phone VARCHAR(20) DEFAULT NULL");
      console.log("Added phone column.");
    }
    if (!fieldNames.includes("status")) {
      await pool.query("ALTER TABLE users ADD COLUMN status VARCHAR(20) DEFAULT 'active'");
      console.log("Added status column.");
    }
    if (!fieldNames.includes("created_at")) {
      await pool.query("ALTER TABLE users ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
      console.log("Added created_at column.");
    }
    if (!fieldNames.includes("updated_at")) {
      await pool.query("ALTER TABLE users ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
      console.log("Added updated_at column.");
    }

    const roleColumn = columns.find(c => c.Field === "role");
    if (roleColumn && !String(roleColumn.Type || "").includes("'cashier'")) {
      await pool.query("ALTER TABLE users MODIFY COLUMN role ENUM('admin','manager','cashier','user') DEFAULT 'user'");
      console.log("Updated role enum values.");
    }

    console.log("Users table migration complete!");
    process.exit(0);
  } catch (err) {
    console.error("Migration failed:", err);
    process.exit(1);
  }
}

migrate();
