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

/**
 * Resolver function that fetches query settings for the remission list.
 * Retrieves the assigned stock and supplier information, then fetches
 * the corresponding query settings for filtering and sorting.
 * 
 * @function querySettingsResolverFn
 * @type {ResolveFn<QuerySettings>}
 * @returns {Promise<QuerySettings>} The 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',
 *   resolve: { querySettings: querySettingsResolverFn },
 *   component: RemissionListComponent
 * }
 */
export const querySettingsResolverFn: 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.fetchQuerySettings({
    assignedStockId: assignedStock.id,
    supplierId: firstSupplier.id,
  });
};
