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

/**
 * Resource for fetching remission capacity based on departments.
 * This resource will fetch the required capacity for the given departments
 * using the RemissionSearchService and RemissionStockService.
 *
 * @param {Function} params - Function that returns an object with departments
 * @returns {Resource} A resource that can be used to fetch remission capacity
 */
export const createRemissionCapacityResource = (
  params: () => {
    departments?: string[];
  },
) => {
  const remissionSearchService = inject(RemissionSearchService);
  const remissionStockService = inject(RemissionStockService);
  const remissionSupplierService = inject(RemissionSupplierService);
  return resource({
    params,
    loader: async ({ abortSignal, params }) => {
      if (!params.departments || params.departments.length === 0) {
        return [];
      }

      const assignedStock = await remissionStockService.fetchAssignedStock();

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

      const suppliers =
        await remissionSupplierService.fetchSuppliers(abortSignal);

      const firstSupplier = suppliers[0]; // Es gibt aktuell nur Blank als Supplier

      if (!firstSupplier || !firstSupplier.id) {
        throw new Error('No Supplier available');
      }

      return await remissionSearchService.fetchRequiredCapacity({
        departments: params.departments,
        supplierId: firstSupplier.id,
        stockId: assignedStock.id,
      });
    },
  });
};
