import { BranchDTO as InventoryBranchDTO } from '@generated/swagger/inventory-api';

/**
 * Branch interface compatible with catalogue-api
 */
export interface CatalogueBranch {
  id: number;
  [key: string]: any;
}

/**
 * Adapter for converting between inventory-api BranchDTO and catalogue-api Branch interface.
 *
 * Handles:
 * - Required vs optional field differences
 * - Field name normalization
 * - Validation of required fields for catalogue operations
 */
export class BranchAdapter {
  private static readonly ADAPTER_NAME = 'BranchAdapter';

  /**
   * Converts inventory-api BranchDTO to catalogue-api Branch format.
   *
   * @param branch - BranchDTO from inventory-api
   * @returns Branch compatible with catalogue-api
   * @throws Error if required fields are missing
   */
  static toCatalogueFormat(branch: InventoryBranchDTO): CatalogueBranch {
    if (!branch.id) {
      const error = new Error('Branch missing required id');
      console.error(
        `[${this.ADAPTER_NAME}] Invalid branch for conversion:`,
        branch,
      );
      throw error;
    }

    // Catalogue-api expects a simple Branch interface with id and flexible additional properties
    const catalogueBranch: CatalogueBranch = {
      id: branch.id,
      // Spread all other properties
      ...branch,
    };

    return catalogueBranch;
  }

  /**
   * Type guard for inventory BranchDTO
   */
  static isValidInventoryBranch(value: unknown): value is InventoryBranchDTO {
    if (typeof value !== 'object' || value === null) return false;

    const branch = value as InventoryBranchDTO;
    return typeof branch.id === 'number';
  }

  /**
   * Type guard for catalogue Branch
   */
  static isValidCatalogueBranch(value: unknown): value is CatalogueBranch {
    if (typeof value !== 'object' || value === null) return false;

    const branch = value as CatalogueBranch;
    return typeof branch.id === 'number';
  }
}
