import { inject, Injectable, resource } from '@angular/core';
import { logger } from '@isa/core/logging';
import { BranchService } from '../services';

@Injectable()
export class BranchesResource {
  #logger = logger({ service: 'BranchesResource' });
  #branchService = inject(BranchService);

  readonly resource = resource({
    loader: async ({ abortSignal }) => {
      this.#logger.debug('Loading all branches');
      const branches = await this.#branchService.fetchBranches(abortSignal);
      this.#logger.debug('Branches loaded', () => ({ count: branches.length }));
      return branches
        .filter(
          (branch) =>
            branch.isOnline &&
            branch.isShippingEnabled &&
            branch.isOrderingEnabled &&
            branch.name !== undefined,
        )
        .sort((a, b) => a.name!.localeCompare(b.name!));
    },
  });
}
