import type { AccountBody } from "../account.service"
import type { FastifyReply, FastifyRequest } from "fastify"
import type { PluginFastifyInstance } from "types"
import { accountSchema } from "../account.schema"

const permissions = ["user.isAdmin"]

export default (fastify: PluginFastifyInstance) => {
  const accountService = fastify.custom.accountService

  const handler = async (
    req: FastifyRequest<{
      Body: AccountBody
    }>,
    reply: FastifyReply,
  ) => {
    try {
      const payload = await accountService.createAccount(
        fastify,
        req.requestParams,
        req.body,
        req.user._id,
      )

      return payload
    } catch (error: any) {
      fastify.log.error(error.message)
      return reply.internalServerError(error.message)
    }
  }

  return {
    handler,
    onRequest: [fastify.authenticate, fastify.checkPermissions(permissions)],
    config: {
      type: "dataCreate",
      broadcastChannels: ["accountCreated"],
    },
    schema: {
      summary: "Create a new account",
      tags: ["core/account"],

      body: accountSchema,
    },
  }
}
