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

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

  // create and pass in the model to your service
  const tagService = createTagService(tagModel)

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

  /*
   * ---------------------------------------------------------------------
   * 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 {
    tag: {
      operations: {
        readAll: tagService._readTags.bind(tagService),
        read: tagService._readTag.bind(tagService),
        readByTitle: tagService._readTagByTitle.bind(tagService),
        create: tagService._createTag.bind(tagService),
        update: tagService._updateTag.bind(tagService),
        delete: tagService._removeTag.bind(tagService),
      },
      keywords: ["tag", "keyword", "buzzword", "label"],
      metadata: {
        description: "Allows labels for every possible data type",
      },
    },
  }
}

export default registerTag
