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

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

  // create and pass in the model to your service
  const userService = createUserService(userModel)

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

  // because the user has more than the standard routes, we need to decorate the model to the instance
  fastify.custom.userModel = userModel

  /*
   * ---------------------------------------------------------------------
   * 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 {
    user: {
      operations: {
        read: userService._readUser.bind(userService),
        readByMail: userService._readUserByEmail.bind(userService),
        readAll: userService._readUsers.bind(userService),
        readCount: userService._readCount.bind(userService),
        create: userService._createUser.bind(userService),
      },
      keywords: ["user", "auth", "identity", "account"],
      metadata: {
        description: "User management and authentication",
      },
    },
  }
}

export default registerUser
