import { PluginFastifyInstance } from "types"
import registerRoutes from "./routes"
import { createModels } from "./interactionLink.model"
import { createInteractionLinkService } from "./interactionLink.service"
import { registerCrud } from "./helpers/crud"
import { registerPayload } from "./helpers/payload"
import { registerSchemas } from "./interactionLink.schema"

const registerInteractionLink = async (fastify: PluginFastifyInstance) => {
  /*
   * ---------------------------------------------------------------------
   * CREATE AND REGISTER ALL YOUR MODELS
   * ---------------------------------------------------------------------
   */
  const interactionLinkModel = createModels(fastify)

  // create and pass in the model to your service
  const interactionLinkService =
    createInteractionLinkService(interactionLinkModel)

  // decorate the service to the instance, so we can easily call it everywhere
  fastify.custom.interactionLinkService = interactionLinkService

  /*
   * ---------------------------------------------------------------------
   * REGISTER ALL YOUR ROUTES
   * ---------------------------------------------------------------------
   */
  try {
    await fastify.register((instance) => registerRoutes(instance))
  } catch (error) {
    fastify.log.error(`Failed to register routes.`, error)
    throw error // Let the application handle the error
  }

  registerPayload(fastify)
  registerCrud(fastify)
  registerSchemas(fastify)

  return {
    interactionLink: {
      operations: {
        readAll: interactionLinkService._readAllInteractionLinks.bind(
          interactionLinkService,
        ),
        read: interactionLinkService._readInteractionLink.bind(
          interactionLinkService,
        ),
        create: interactionLinkService._createInteractionLink.bind(
          interactionLinkService,
        ),
        delete: interactionLinkService._removeInteractionLink.bind(
          interactionLinkService,
        ),
      },
      keywords: ["interaction", "link", "connection", "relation"],
      metadata: {
        description: "Links between interactive elements",
      },
    },
  }
}

export default registerInteractionLink
