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

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

  // create and pass in the model to your service
  const projectService = createProjectService(projectModel)

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

  /*
   * ---------------------------------------------------------------------
   * 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 {
    project: {
      operations: {
        read: projectService._readProject.bind(projectService),
        readMain: projectService._readMainProject.bind(projectService),
        readAll: projectService._readProjects.bind(projectService),
        create: projectService._createProject.bind(projectService),
        update: projectService._updateProject.bind(projectService),
      },
      keywords: ["project", "space"],
      metadata: {
        description: "The space the user is using the app in.",
      },
    },
  }
}

export default registerProject
