import { ContractHandlers as ContractHandlersOrig, SELF_REGISTER_HANDLER_NAME } from '@coinweb/contract-kit';
import { selfRegisterHandler } from '@coinweb/self-register';
import { queue } from 'lib/onchain';

import { addMethodHandler, ContractHandlers, executeHandler } from '../../../contract-kit';
import { executor } from '../../executor';
import { mutexMethods } from '../../mutex';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const constructCwebMain = (methods: Record<string, (...args: any[]) => Promise<void>>) => async () => {
  const module: ContractHandlers = { handlers: {} };

  Object.entries(methods).forEach(([name, handler]) => {
    if (name.startsWith('_')) {
      throw new Error('Do not start method names with "_" because they are reserved for internal use');
    }

    addMethodHandler(module, name, executor(handler));
  });

  Object.entries(mutexMethods).forEach(([name, handler]) => {
    addMethodHandler(module, name, handler);
  });

  addMethodHandler(module, SELF_REGISTER_HANDLER_NAME, selfRegisterHandler);

  queue.applyQueue(module as ContractHandlersOrig, []);

  await executeHandler(module);
};
