/**
 * Adapter for handling catalogProductNumber conversions between API boundaries.
 *
 * checkout-api uses string, catalogue-api uses number.
 * This adapter provides safe bidirectional conversion with validation.
 */
export class ProductNumberAdapter {
  private static readonly ADAPTER_NAME = 'ProductNumberAdapter';

  /**
   * Converts string catalogProductNumber to number (checkout-api → catalogue-api)
   *
   * @param value - String product number from checkout-api
   * @returns Number product number or undefined if invalid
   */
  static toNumber(value: string | undefined): number | undefined {
    if (value === undefined || value === null || value === '') {
      return undefined;
    }

    const parsed = parseInt(value, 10);

    if (isNaN(parsed)) {
      console.warn(
        `[${this.ADAPTER_NAME}] Invalid catalogProductNumber for conversion:`,
        value,
      );
      return undefined;
    }

    return parsed;
  }

  /**
   * Converts number catalogProductNumber to string (catalogue-api → checkout-api)
   *
   * @param value - Number product number from catalogue-api
   * @returns String product number or undefined if invalid
   */
  static toString(value: number | undefined): string | undefined {
    if (value === undefined || value === null) {
      return undefined;
    }

    return String(value);
  }

  /**
   * Type guard to check if a value is a valid product number (string or number)
   */
  static isValid(value: unknown): value is string | number {
    if (typeof value === 'string') {
      return !isNaN(parseInt(value, 10));
    }
    if (typeof value === 'number') {
      return !isNaN(value) && isFinite(value);
    }
    return false;
  }
}
