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

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

  #params = signal<
    { branchId: number | null } | { branchNumber: string | null }
  >({ branchId: null });

  params(
    params: { branchId: number | null } | { branchNumber: string | null },
  ) {
    this.#params.set(params);
  }

  readonly resource = resource({
    params: () => this.#params(),
    loader: async ({ params, abortSignal }) => {
      if ('branchNumber' in params && !params.branchNumber) {
        return null;
      }
      if ('branchId' in params && !params.branchId) {
        return null;
      }
      this.#logger.debug('Loading branch', () => params);
      const res = await this.#branchService.fetchBranches(abortSignal);
      const branch = res.find((b) => {
        if ('branchId' in params) {
          return b.id === params.branchId;
        } else {
          return b.branchNumber === params.branchNumber;
        }
      });
      this.#logger.debug('Branch loaded', () => ({
        found: !!branch,
        branchId: branch?.id,
      }));
      return branch;
    },
  });
}
