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

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

  // create and pass in the model to your service
  const workSessionService = createWorkSessionService(workSessionModel)

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

  /*
   * ---------------------------------------------------------------------
   * 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 {
    workSession: {
      operations: {
        read: workSessionService._readWorkSession.bind(workSessionService),
        readAll: workSessionService._readWorkSessions.bind(workSessionService),
        create: workSessionService._createWorkSession.bind(workSessionService),
        update: workSessionService._updateWorkSession.bind(workSessionService),
      },
      keywords: ["workSession", "session"],
      metadata: {
        description: "A work session for user interactions.",
      },
    },
  }
}

export default registerWorkSession
