import type { PluginFastifyInstance } from "types"
import registerRoutes from "./routes"
import { createModels } from "./composition.model"
import { createCompositionService } from "./composition.service"
import { registerPayload } from "./helpers/payload"
import { registerCrud } from "./helpers/crud"
import { compositionSchema, registerSchemas } from "./composition.schema"

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

  // create and pass in the model to your service
  const compositionService = await createCompositionService(compositionModel)

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

  /*
   * ---------------------------------------------------------------------
   * 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
  }

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

  return {
    composition: {
      schema: compositionSchema,
      operations: {
        readAll:
          compositionService._readAllCompositions.bind(compositionService),
        read: compositionService._readComposition.bind(compositionService),
        create: compositionService._createComposition.bind(compositionService),
        update: compositionService._updateComposition.bind(compositionService),
        delete: compositionService._removeComposition.bind(compositionService),
      },
      keywords: ["composition", "content", "layout", "structure"],
      metadata: {
        description: "Core composition management",
        version: "1.0.0",
      },
    },
  }
}

export default registerComposition
