module.exports = {
  /**
   * @param {import("sequelize").QueryInterface} queryInterface
   * @param {import("sequelize").Sequelize} Sequelize
   * @returns {Promise<void>}
   */
  async up(queryInterface, Sequelize) {
    const roles = await queryInterface.sequelize.query(
      `SELECT id FROM roles WHERE name = 'Trust & Safety Lead'`,
      { type: queryInterface.sequelize.QueryTypes.SELECT }
    );
    if (!roles || roles.length === 0) return;
    const roleId = roles[0].id;

    const permissionsToGrant = [
      'READ_VERIFICATION_SUBMISSIONS',
      'UPDATE_VERIFICATION_SUBMISSIONS',
      'READ_VERIFICATION_EVIDENCES',
      'READ_REVIEWS',
      'UPDATE_REVIEWS',
      'DELETE_REVIEWS',
      'READ_BUSINESSES',
      'READ_USERS'
    ];

    const permissions = await queryInterface.sequelize.query(
      `SELECT id, name FROM permissions WHERE name IN (${permissionsToGrant.map(p => `'${p}'`).join(',')})`,
      { type: queryInterface.sequelize.QueryTypes.SELECT }
    );

    const rolesPermissions = [];
    for (const p of permissions) {
      const existing = await queryInterface.sequelize.query(
        `SELECT * FROM "rolesPermissionsPermissions" WHERE "roles_permissionsId" = '${roleId}' AND "permissionId" = '${p.id}'`,
        { type: queryInterface.sequelize.QueryTypes.SELECT }
      );
      if (existing.length === 0) {
        rolesPermissions.push({
          roles_permissionsId: roleId,
          permissionId: p.id,
          createdAt: new Date(),
          updatedAt: new Date()
        });
      }
    }

    if (rolesPermissions.length > 0) {
      await queryInterface.bulkInsert('rolesPermissionsPermissions', rolesPermissions);
    }
  },

  async down(queryInterface, Sequelize) {
    // Optionally implement down migration
  },
};