// apps/web/src/server/invoicing/registry.ts
import { NoopProvider } from './noop';
import { MorningProvider } from './morning';
import { ICountProvider } from './icount';
import { NotImplementedProvider } from './not-implemented';
import type { VendorInvoiceProvider } from './types';

export const vendorInvoiceProviders: Record<string, VendorInvoiceProvider> = {
  morning: new MorningProvider(),
  icount: new ICountProvider(),
  rivhit: new NotImplementedProvider('rivhit'),
  invoice4u: new NotImplementedProvider('invoice4u'),
  easycount: new NotImplementedProvider('easycount'),
  meshulam: new NotImplementedProvider('meshulam'),
  self_handled: new NoopProvider(),
};

/** Only providers that are fully implemented and selectable by vendors. */
export const implementedVendorInvoiceProviders: Record<string, VendorInvoiceProvider> =
  Object.fromEntries(
    Object.entries(vendorInvoiceProviders).filter(
      ([, p]) => !(p instanceof NotImplementedProvider),
    ),
  );

export class ProviderNotReadyError extends Error {
  constructor(public kind: string) {
    super(`invoice_provider_not_ready:${kind}`);
    this.name = 'ProviderNotReadyError';
  }
}

export function getVendorInvoiceProvider(kind: string): VendorInvoiceProvider {
  const p = vendorInvoiceProviders[kind];
  if (!p) throw new Error(`unknown_invoice_provider:${kind}`);
  if (p instanceof NotImplementedProvider) throw new ProviderNotReadyError(kind);
  return p;
}
