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

/**
 * Resolver function that fetches department-specific query settings for the remission list.
 * Similar to querySettingsResolverFn but fetches department-specific settings.
 * 
 * @function querySettingsDepartmentResolverFn
 * @type {ResolveFn<QuerySettings>}
 * @returns {Promise<QuerySettings>} The department query settings for the current stock and supplier
 * @throws {Error} When no assigned stock is available
 * @throws {Error} When no supplier is available
 * 
 * @example
 * // In route configuration
 * {
 *   path: 'remissions/department',
 *   resolve: { querySettings: querySettingsDepartmentResolverFn },
 *   component: RemissionDepartmentListComponent
 * }
 */
export const querySettingsDepartmentResolverFn: ResolveFn<
  QuerySettings
> = async () => {
  const remissionSearchService = inject(RemissionSearchService);
  const remissionStockService = inject(RemissionStockService);
  const remissionSupplierService = inject(RemissionSupplierService);

  const assignedStock = await remissionStockService.fetchAssignedStock();

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

  const suppliers = await remissionSupplierService.fetchSuppliers();

  const firstSupplier = suppliers[0]; // Currently only one supplier exists

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

  return remissionSearchService.fetchQueryDepartmentSettings({
    assignedStockId: assignedStock.id,
    supplierId: firstSupplier.id,
  });
};
