import { inject, Injectable } from '@angular/core';
import { StockService, BranchDTO } from '@generated/swagger/inventory-api';
import { ResponseArgsError, takeUntilAborted } from '@isa/common/data-access';
import { logger } from '@isa/core/logging';
import { firstValueFrom } from 'rxjs';

/**
 * Service for branch/stock operations.
 *
 * @remarks
 * This service handles inventory operations:
 * - Retrieving the default/current branch for the user
 *
 * Note: This service is in remission-data-access as a temporary location.
 * It will be moved to inventory-data-access when that module is created.
 */
@Injectable({ providedIn: 'root' })
export class BranchService {
  #logger = logger(() => ({ service: 'BranchService' }));
  readonly #stockService = inject(StockService);

  /**
   * Gets the default branch from the inventory service.
   *
   * @param abortSignal - Optional signal to abort the operation
   * @returns Promise resolving to branch data
   * @throws {Error} If branch retrieval fails
   */
  async getDefaultBranch(abortSignal?: AbortSignal): Promise<BranchDTO> {
    let req$ = this.#stockService.StockCurrentBranch();
    if (abortSignal) req$ = req$.pipe(takeUntilAborted(abortSignal));

    const res = await firstValueFrom(req$);

    if (res.error) {
      const error = new ResponseArgsError(res);
      this.#logger.error('Failed to get default branch', error);
      throw error;
    }

    const branch = res.result;

    if (!branch) {
      const error = new Error('No branch data returned');
      this.#logger.error('Failed to get default branch', error);
      throw error;
    }

    return {
      id: branch.id,
      name: branch.name,
      address: branch.address,
      branchType: branch.branchType,
      branchNumber: branch.branchNumber,
      changed: branch.changed,
      created: branch.created,
      isDefault: branch.isDefault,
      isOnline: branch.isOnline,
      key: branch.key,
      label: branch.label,
      pId: branch.pId,
      shortName: branch.shortName,
      status: branch.status,
      version: branch.version,
    };
  }
}
