'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [companies, users] = await Promise.all([
      queryInterface.sequelize.query("SELECT id FROM company WHERE code = 'COMP001' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id FROM user WHERE username = 'admin' LIMIT 1")
    ]);

    const companyId = companies[0].length > 0 ? companies[0][0].id : null;
    const userId = users[0].length > 0 ? users[0][0].id : null;

    const roles = [
      { company_id: null, role_code: 'SUPER_ADMIN', role_name: 'Super Administrator', description: 'System super administrator with all permissions', is_system_role: 1, status: 'ACTIVE' },
      { company_id: companyId, role_code: 'ADMIN', role_name: 'Administrator', description: 'Company administrator', is_system_role: 0, status: 'ACTIVE' },
      { company_id: companyId, role_code: 'MANAGER', role_name: 'Manager', description: 'Department manager', is_system_role: 0, status: 'ACTIVE' },
      { company_id: companyId, role_code: 'USER', role_name: 'User', description: 'Standard user', is_system_role: 0, status: 'ACTIVE' }
    ];
    const dialect = queryInterface.sequelize.getDialect ? queryInterface.sequelize.getDialect() : 'mysql';
    if (dialect === 'mysql' || dialect === 'mariadb') {
      for (const r of roles) {
        await queryInterface.sequelize.query(
          `INSERT IGNORE INTO role (company_id, role_code, role_name, description, is_system_role, status, created_by, created_at, updated_at)
           VALUES (:company_id, :role_code, :role_name, :description, :is_system_role, :status, :created_by, NOW(), NOW())`,
          { replacements: { ...r, created_by: userId } }
        );
      }
    } else {
      await queryInterface.bulkInsert('role', roles.map((r) => ({ ...r, is_system_role: !!r.is_system_role, created_by: userId, created_at: new Date(), updated_at: new Date() })), { ignoreDuplicates: true });
    }
  },

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

