'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // Add MASTER.ORGANIZATION.VIEW permission if it doesn't exist (required for Organization menu in sidebar)
    const [rows] = await queryInterface.sequelize.query(
      `SELECT id FROM permission WHERE permission_code = 'MASTER.ORGANIZATION.VIEW' LIMIT 1`
    );

    if (!rows || rows.length === 0) {
      await queryInterface.bulkInsert('permission', [{
        permission_code: 'MASTER.ORGANIZATION.VIEW',
        permission_name: 'Organization - View',
        module: 'MASTER',
        resource: 'organization',
        action: 'READ',
        operation: 'READ',
        is_system_permission: true,
        status: 'ACTIVE',
        created_at: new Date(),
        updated_at: new Date()
      }], { ignoreDuplicates: true });
    }

    // Add MASTER.ORGANIZATION.VIEW to IT_ADMIN and HR_MGR roles (for existing DBs)
    const [[permRows], [roleRows]] = await Promise.all([
      queryInterface.sequelize.query(`SELECT id FROM permission WHERE permission_code = 'MASTER.ORGANIZATION.VIEW' LIMIT 1`),
      queryInterface.sequelize.query(`SELECT id FROM role WHERE role_code IN ('IT_ADMIN', 'HR_MGR')`)
    ]);
    const permId = permRows?.[0]?.id;
    if (permId && roleRows?.length > 0) {
      const rolePerms = roleRows.map(r => ({
        role_id: r.id,
        permission_id: permId,
        status: 'ACTIVE',
        created_at: new Date(),
        updated_at: new Date()
      }));
      await queryInterface.bulkInsert('role_permission', rolePerms, { ignoreDuplicates: true });
    }
  },

  async down(queryInterface, Sequelize) {
    const [permRows] = await queryInterface.sequelize.query(
      `SELECT id FROM permission WHERE permission_code = 'MASTER.ORGANIZATION.VIEW' LIMIT 1`
    );
    const permId = permRows?.[0]?.id;
    if (permId) {
      await queryInterface.bulkDelete('role_permission', { permission_id: permId });
    }
    await queryInterface.bulkDelete('permission', {
      permission_code: 'MASTER.ORGANIZATION.VIEW'
    });
  }
};
