import { BadRequestException } from '@nestjs/common';

/**
 * Decodes a Base64 encoded string to its original UTF-8 string representation
 *
 * @param base64string - The Base64 encoded string to decode
 * @returns The decoded UTF-8 string
 * @throws {BadRequestException} When the input is not valid Base64 encoded data
 *
 * @example
 * // Returns: "Hello World"
 * decodeBase64("SGVsbG8gV29ybGQ=");
 *
 * @example
 * // Throws BadRequestException
 * decodeBase64("Invalid!@#$");
 */
export const decodeBase64 = (base64string: string): string => {
  try {
    // Convert Base64 string to Buffer using base64 encoding
    // Then convert Buffer to UTF-8 string
    const decodedValue = Buffer.from(base64string, 'base64').toString('utf-8');
    return decodedValue;
  } catch (error) {
    // Throw HTTP 400 Bad Request when input cannot be decoded
    // This could happen due to:
    // - Invalid Base64 characters
    // - Incorrect Base64 padding
    // - Non-UTF-8 compatible binary data
    throw new BadRequestException('Invalid Base64 encoding');
  }
};
