import type { PluginFastifyInstance, PluginOptions } from "@raclettejs/core"
import registerAccount from "./datatypes/account"
import registerComposition from "./datatypes/composition"
import registerInteractionLink from "./datatypes/interactionLink"
import registerTag from "./datatypes/tag"
import registerUser from "./datatypes/user"
import registerProject from "./datatypes/project"
import registerWorkSession from "./datatypes/workSession"
import { PluginContract } from "@c/contracting/contractTypes"

const racletteCorePlugin = async (
  fastify: PluginFastifyInstance,
  opts: PluginOptions,
) => {
  fastify.log.info("raclette Core Plugin")

  // Register all datatypes in parallel and collect their contracts
  const contractRegistrations = await Promise.all([
    registerAccount(fastify),
    registerComposition(fastify),
    registerInteractionLink(fastify),
    registerProject(fastify),
    registerTag(fastify),
    registerUser(fastify),
    registerWorkSession(fastify),
  ])

  // Combine all contract snippets into one plugin contract
  const pluginContract: PluginContract = contractRegistrations.reduce(
    (acc, contract) => {
      if (contract && typeof contract === "object") {
        return {
          ...acc,
          ...contract,
        }
      }

      return acc
    },
    {},
  )

  // Register the complete contract
  fastify.registerPluginContract(pluginContract)
}

export default racletteCorePlugin
