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

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

    const permissions = [
      { id: uuid(), name: 'CREATE_CLAIM_REQUESTS', createdAt, updatedAt },
      { id: uuid(), name: 'READ_CLAIM_REQUESTS', createdAt, updatedAt },
      { id: uuid(), name: 'UPDATE_CLAIM_REQUESTS', createdAt, updatedAt },
      { id: uuid(), name: 'DELETE_CLAIM_REQUESTS', createdAt, updatedAt },
    ];

    await queryInterface.bulkInsert('permissions', permissions);

    const roles = await queryInterface.sequelize.query(
      `SELECT id, name FROM "roles" WHERE name IN ('Administrator', 'Platform Owner', 'Verified Business Owner')`,
      { type: queryInterface.sequelize.QueryTypes.SELECT }
    );

    const adminRole = roles.find(r => r.name === 'Administrator');
    const ownerRole = roles.find(r => r.name === 'Platform Owner');
    const vboRole = roles.find(r => r.name === 'Verified Business Owner');

    const rolePerms = [];

    permissions.forEach(p => {
      if (adminRole) {
        rolePerms.push({
          createdAt,
          updatedAt,
          roles_permissionsId: adminRole.id,
          permissionId: p.id,
        });
      }
      if (ownerRole) {
        rolePerms.push({
          createdAt,
          updatedAt,
          roles_permissionsId: ownerRole.id,
          permissionId: p.id,
        });
      }
      // VBO can only create and read
      if (vboRole && (p.name === 'CREATE_CLAIM_REQUESTS' || p.name === 'READ_CLAIM_REQUESTS')) {
        rolePerms.push({
          createdAt,
          updatedAt,
          roles_permissionsId: vboRole.id,
          permissionId: p.id,
        });
      }
    });

    await queryInterface.bulkInsert('rolesPermissionsPermissions', rolePerms);
  },

  async down(queryInterface) {
    // No need to implement down for this simple permission addition in a dev environment
  }
};
