'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const createdAt = new Date();
    const updatedAt = new Date();

    const [roles] = await queryInterface.sequelize.query(
      `SELECT id FROM roles WHERE name = 'Verified Business Owner';`
    );

    const [permissions] = await queryInterface.sequelize.query(
      `SELECT id FROM permissions WHERE name = 'DELETE_BUSINESS_PHOTOS';`
    );

    if (roles.length > 0 && permissions.length > 0) {
      const roleId = roles[0].id;
      const permissionId = permissions[0].id;

      // Check if it already exists to avoid duplicates
      const [existing] = await queryInterface.sequelize.query(
        `SELECT * FROM "rolesPermissionsPermissions" WHERE "roles_permissionsId" = '${roleId}' AND "permissionId" = '${permissionId}';`
      );

      if (existing.length === 0) {
        await queryInterface.bulkInsert('rolesPermissionsPermissions', [
          {
            createdAt,
            updatedAt,
            roles_permissionsId: roleId,
            permissionId: permissionId,
          },
        ]);
      }
    }
  },

  down: async (queryInterface, Sequelize) => {
    // Logic to remove the permission if needed
  }
};
