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

import { MermaidGeneratedSharedModule, ArchitectureGeneratedModule } from '../generated/module.js';
import { ArchitectureTokenBuilder } from './tokenBuilder.js';
import { ArchitectureValueConverter } from './valueConverter.js';

/**
 * Declaration of `Architecture` services.
 */
interface ArchitectureAddedServices {
  parser: {
    TokenBuilder: ArchitectureTokenBuilder;
    ValueConverter: ArchitectureValueConverter;
  };
}

/**
 * Union of Langium default services and `Architecture` services.
 */
export type ArchitectureServices = LangiumCoreServices & ArchitectureAddedServices;

/**
 * Dependency injection module that overrides Langium default services and
 * contributes the declared `Architecture` services.
 */
export const ArchitectureModule: Module<
  ArchitectureServices,
  PartialLangiumCoreServices & ArchitectureAddedServices
> = {
  parser: {
    TokenBuilder: () => new ArchitectureTokenBuilder(),
    ValueConverter: () => new ArchitectureValueConverter(),
  },
};

/**
 * 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 createArchitectureServices(
  context: DefaultSharedCoreModuleContext = EmptyFileSystem
): {
  shared: LangiumSharedCoreServices;
  Architecture: ArchitectureServices;
} {
  const shared: LangiumSharedCoreServices = inject(
    createDefaultSharedCoreModule(context),
    MermaidGeneratedSharedModule
  );
  const Architecture: ArchitectureServices = inject(
    createDefaultCoreModule({ shared }),
    ArchitectureGeneratedModule,
    ArchitectureModule
  );
  shared.ServiceRegistry.register(Architecture);
  return { shared, Architecture };
}
