import dotenv from 'dotenv';
import { Sequelize } from 'sequelize';

dotenv.config();

const sequelize = new Sequelize(
  process.env.MYSQL_DATABASE || 'fix_it_auto_care',
  process.env.MYSQL_USER || 'root',
  process.env.MYSQL_PASSWORD || '',
  {
    host: process.env.MYSQL_HOST || '127.0.0.1',
    port: Number(process.env.MYSQL_PORT || 3306),
    dialect: 'mysql',
    logging: false,
  }
);

async function run() {
  try {
    await sequelize.authenticate();
    console.log('Connected to DB');

    // Alter table
    await sequelize.query("ALTER TABLE users MODIFY COLUMN role ENUM('customer','employee','admin','super_admin') NOT NULL DEFAULT 'customer';");
    console.log('Altered table successfully');

    // Insert super admin if not exists
    const [results] = await sequelize.query("SELECT * FROM users WHERE phone = '9990000000'");
    if (results.length === 0) {
      await sequelize.query("INSERT INTO users (name, phone, role, created_at) VALUES ('Platform Super Admin', '9990000000', 'super_admin', NOW());");
      console.log('Super admin inserted');
    } else {
      console.log('Super admin already exists');
    }
  } catch (error) {
    console.error('Migration error:', error);
  } finally {
    await sequelize.close();
  }
}

run();
