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

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

  // create and pass in the model to your service
  const accountService = createAccountService(accountModel)

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

  /*
   * ---------------------------------------------------------------------
   * 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 {
    account: {
      operations: {
        readAll: accountService._readAccounts.bind(accountService),
        read: accountService._readAccount.bind(accountService),
        create: accountService._createAccount.bind(accountService),
        update: accountService._updateAccount.bind(accountService),
      },
      keywords: ["account"],
      metadata: {
        description: "An account handles users and projects",
      },
    },
  }
}

export default registerAccount
