import { inject, Injectable } from '@angular/core';
import { StoreCheckoutBranchService } from '@generated/swagger/checkout-api';
import { ResponseArgsError, takeUntilAborted } from '@isa/common/data-access';
import { logger } from '@isa/core/logging';
import { firstValueFrom } from 'rxjs';
import { Cache, CacheTimeToLive, InFlight } from '@isa/common/decorators';
import { Branch } from '../schemas';

@Injectable({ providedIn: 'root' })
export class BranchService {
  #logger = logger(() => ({ service: 'BranchService' }));
  #branchService = inject(StoreCheckoutBranchService);

  @Cache({ ttl: CacheTimeToLive.fiveMinutes })
  @InFlight()
  async fetchBranches(abortSignal?: AbortSignal): Promise<Branch[]> {
    let req$ = this.#branchService.StoreCheckoutBranchGetBranches({});

    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 fetch branches', error);
      throw error;
    }

    return res.result as Branch[];
  }
}
