'use strict';

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

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

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

    const dialect = queryInterface.sequelize.getDialect ? queryInterface.sequelize.getDialect() : 'mysql';
    if (dialect === 'mysql' || dialect === 'mariadb') {
      for (const perm of permissions[0]) {
        await queryInterface.sequelize.query(
          `INSERT IGNORE INTO role_permission (role_id, permission_id, status, created_by, created_at, updated_at)
           VALUES (:role_id, :permission_id, 'ACTIVE', :created_by, NOW(), NOW())`,
          { replacements: { role_id: roleId, permission_id: perm.id, created_by: userId } }
        );
      }
    } else {
      const rolePermissions = permissions[0].map(perm => ({
        role_id: roleId,
        permission_id: perm.id,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      }));
      await queryInterface.bulkInsert('role_permission', rolePermissions, { ignoreDuplicates: true });
    }
  },

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

