'use strict';

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

    if (users[0].length === 0 || roles[0].length === 0) return;

    const userId = users[0][0].id;
    const roleId = roles[0][0].id;

    const dialect = queryInterface.sequelize.getDialect ? queryInterface.sequelize.getDialect() : 'mysql';
    if (dialect === 'mysql' || dialect === 'mariadb') {
      await queryInterface.sequelize.query(
        `INSERT IGNORE INTO user_role (user_id, role_id, status, created_by, created_at, updated_at)
         VALUES (:user_id, :role_id, 'ACTIVE', :created_by, NOW(), NOW())`,
        { replacements: { user_id: userId, role_id: roleId, created_by: userId } }
      );
    } else {
      await queryInterface.bulkInsert('user_role', [{ user_id: userId, role_id: roleId, status: 'ACTIVE', created_by: userId, created_at: new Date(), updated_at: new Date() }], { ignoreDuplicates: true });
    }
  },

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

