const { v4: uuid } = require("uuid");

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

    const roles = await queryInterface.sequelize.query(
      `SELECT id, name FROM "roles";`,
      { type: queryInterface.sequelize.QueryTypes.SELECT }
    );

    const permissions = await queryInterface.sequelize.query(
      `SELECT id, name FROM "permissions";`,
      { type: queryInterface.sequelize.QueryTypes.SELECT }
    );

    const getRoleId = (name) => roles.find(r => r.name === name)?.id;
    const getPermId = (name) => permissions.find(p => p.name === name)?.id;

    const vboRoleId = getRoleId("Verified Business Owner");
    const createDisputesPermId = getPermId("CREATE_DISPUTES");

    if (vboRoleId && createDisputesPermId) {
      const existing = await queryInterface.sequelize.query(
        `SELECT * FROM "rolesPermissionsPermissions" WHERE "roles_permissionsId" = '${vboRoleId}' AND "permissionId" = '${createDisputesPermId}';`,
        { type: queryInterface.sequelize.QueryTypes.SELECT }
      );
      if (existing.length === 0) {
        await queryInterface.bulkInsert("rolesPermissionsPermissions", [{
          createdAt,
          updatedAt,
          roles_permissionsId: vboRoleId,
          permissionId: createDisputesPermId
        }]);
      }
    }
  },

  async down(queryInterface) {
  }
};
