import { computed, inject, Injectable, resource, signal } from '@angular/core';
import { DisplayOrderItemSubset } from '../schemas';
import { OrderRewardCollectFacade } from '../facades';

@Injectable()
export class OrderItemSubsetResource {
  #orderRewardCollectFacade = inject(OrderRewardCollectFacade);

  #orderItemSubsetIds = signal<number[] | undefined>(undefined);

  #orderItemSubsetsResource = resource({
    params: computed(() => ({
      orderItemSubsetIds: this.#orderItemSubsetIds(),
    })),
    loader: async ({
      params,
      abortSignal,
    }): Promise<DisplayOrderItemSubset[]> => {
      if (!params?.orderItemSubsetIds?.length) {
        return [];
      }

      const results: DisplayOrderItemSubset[] = [];
      for (const id of params.orderItemSubsetIds) {
        const result = await this.#orderRewardCollectFacade.getOrderItemSubset(
          { orderItemSubsetId: id },
          abortSignal,
        );
        if (result) {
          results.push(result);
        }
      }
      return results;
    },
    defaultValue: [],
  });

  readonly orderItemSubsets = this.#orderItemSubsetsResource.value.asReadonly();
  readonly loading = this.#orderItemSubsetsResource.isLoading;
  readonly error = computed(
    () => this.#orderItemSubsetsResource.error()?.message ?? null,
  );

  loadOrderItemSubsets(orderItemSubsetIds: number[] | undefined) {
    this.#orderItemSubsetIds.set(orderItemSubsetIds);
  }

  refresh() {
    this.#orderItemSubsetsResource.reload();
  }
}
