import { inject, resource } from '@angular/core';
import { RemissionStockService } from '@isa/remission/data-access';

export const createRemissionInStockResource = (
  params: () => {
    itemIds: string[];
  },
) => {
  const remissionStockService = inject(RemissionStockService);
  return resource({
    params,
    loader: async ({ abortSignal, params }) => {
      if (!params?.itemIds || params.itemIds.length === 0) {
        return;
      }

      const assignedStock =
        await remissionStockService.fetchAssignedStock(abortSignal);

      if (!assignedStock || !assignedStock.id) {
        throw new Error('No current stock available');
      }

      const itemIds = params.itemIds.map((id) => Number(id));

      if (itemIds.some((id) => isNaN(id))) {
        throw new Error('Invalid Catalog Product Number provided');
      }

      return await remissionStockService.fetchStockInfos(
        {
          itemIds,
          stockId: assignedStock.id,
        },
        abortSignal,
      );
    },
  });
};
