'use strict';
const bcrypt = require('bcryptjs');

module.exports = {
  async up(queryInterface, Sequelize) {
    const [companies] = await queryInterface.sequelize.query(
      "SELECT id FROM company WHERE code = 'COMP001' LIMIT 1"
    );
    
    if (companies.length === 0) return;
    
    const companyId = companies[0].id;
    const passwordHash = await bcrypt.hash('Admin@123', 10);
    const dialect = queryInterface.sequelize.getDialect ? queryInterface.sequelize.getDialect() : 'mysql';
    const row = {
      company_id: companyId,
      username: 'admin',
      email: 'admin@abcmanufacturing.com',
      password_hash: passwordHash,
      first_name: 'System',
      last_name: 'Administrator',
      is_super_admin: 1,
      is_active: 1,
      is_locked: 0,
      status: 'ACTIVE'
    };
    if (dialect === 'mysql' || dialect === 'mariadb') {
      await queryInterface.sequelize.query(
        `INSERT IGNORE INTO user (company_id, username, email, password_hash, first_name, last_name, is_super_admin, is_active, is_locked, status, created_at, updated_at)
         VALUES (:company_id, :username, :email, :password_hash, :first_name, :last_name, :is_super_admin, :is_active, :is_locked, :status, NOW(), NOW())`,
        { replacements: row }
      );
    } else {
      await queryInterface.bulkInsert('user', [{ ...row, is_super_admin: true, is_active: true, is_locked: false, created_at: new Date(), updated_at: new Date() }], { ignoreDuplicates: true });
    }
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.bulkDelete('user', null, {});
  }
};

