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

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

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

    let readTransactionsId;
    if (permissions.length === 0) {
      readTransactionsId = uuid();
      await queryInterface.bulkInsert("permissions", [
        { id: readTransactionsId, name: 'READ_TRANSACTIONS', createdAt, updatedAt },
        { id: uuid(), name: 'CREATE_TRANSACTIONS', createdAt, updatedAt },
        { id: uuid(), name: 'UPDATE_TRANSACTIONS', createdAt, updatedAt },
        { id: uuid(), name: 'DELETE_TRANSACTIONS', createdAt, updatedAt },
      ]);
    } else {
      readTransactionsId = permissions[0].id;
    }

    const [roles] = await queryInterface.sequelize.query(
      `SELECT id, name FROM roles`
    );

    const rolesToGrant = ['Super Administrator', 'Administrator', 'PlatformOwner', 'FirmOwner', 'SeniorAccountant', 'Accountant', 'MerchantUser', 'Public'];
    const rolePermissions = [];

    for (const role of roles) {
      if (rolesToGrant.includes(role.name)) {
        rolePermissions.push({
          createdAt,
          updatedAt,
          roles_permissionsId: role.id,
          permissionId: readTransactionsId
        });
      }
    }

    if (rolePermissions.length > 0) {
      // Use a raw query with ON CONFLICT to avoid duplicate key errors if it runs multiple times
      for (const rp of rolePermissions) {
        await queryInterface.sequelize.query(
          `INSERT INTO "rolesPermissionsPermissions" ("createdAt", "updatedAt", "roles_permissionsId", "permissionId")
           VALUES ('${rp.createdAt.toISOString()}', '${rp.updatedAt.toISOString()}', '${rp.roles_permissionsId}', '${rp.permissionId}')
           ON CONFLICT DO NOTHING`
        );
      }
    }
  },

  async down() {
    // Optional: remove permissions if needed
  }
};