import type { FastifyReply, FastifyRequest } from "fastify"
import { PluginFastifyInstance } from "types"
import { userCreateSchema, type UserCreate } from "../user.schema"

const permissions = ["user.isAdmin"]

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

  const handler = async (
    req: FastifyRequest<{ Body: UserCreate }>,
    reply: FastifyReply,
  ) => {
    try {
      const payloadWithUser = await userService.createUser(
        fastify,
        req.requestParams,
        { ...req.body },
      )

      return payloadWithUser
    } 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: ["userCreated"],
    },
    schema: {
      summary: "Create a new user",
      description: "Create a new user with the provided details",
      tags: ["core/user"],
      body: userCreateSchema,
    },
  }
}
