import type {
  DefaultSharedCoreModuleContext,
  LangiumCoreServices,
  LangiumSharedCoreServices,
  Module,
  PartialLangiumCoreServices,
} from 'langium';
import {
  EmptyFileSystem,
  createDefaultCoreModule,
  createDefaultSharedCoreModule,
  inject,
} from 'langium';

import { MermaidGeneratedSharedModule, PieGeneratedModule } from '../generated/module.js';
import { PieTokenBuilder } from './tokenBuilder.js';
import { PieValueConverter } from './valueConverter.js';

/**
 * Declaration of `Pie` services.
 */
interface PieAddedServices {
  parser: {
    TokenBuilder: PieTokenBuilder;
    ValueConverter: PieValueConverter;
  };
}

/**
 * Union of Langium default services and `Pie` services.
 */
export type PieServices = LangiumCoreServices & PieAddedServices;

/**
 * Dependency injection module that overrides Langium default services and
 * contributes the declared `Pie` services.
 */
export const PieModule: Module<PieServices, PartialLangiumCoreServices & PieAddedServices> = {
  parser: {
    TokenBuilder: () => new PieTokenBuilder(),
    ValueConverter: () => new PieValueConverter(),
  },
};

/**
 * Create the full set of services required by Langium.
 *
 * First inject the shared services by merging two modules:
 *  - Langium default shared services
 *  - Services generated by langium-cli
 *
 * Then inject the language-specific services by merging three modules:
 *  - Langium default language-specific services
 *  - Services generated by langium-cli
 *  - Services specified in this file
 * @param context - Optional module context with the LSP connection
 * @returns An object wrapping the shared services and the language-specific services
 */
export function createPieServices(context: DefaultSharedCoreModuleContext = EmptyFileSystem): {
  shared: LangiumSharedCoreServices;
  Pie: PieServices;
} {
  const shared: LangiumSharedCoreServices = inject(
    createDefaultSharedCoreModule(context),
    MermaidGeneratedSharedModule
  );
  const Pie: PieServices = inject(
    createDefaultCoreModule({ shared }),
    PieGeneratedModule,
    PieModule
  );
  shared.ServiceRegistry.register(Pie);
  return { shared, Pie };
}
