import type { Static } from "@sinclair/typebox"
import type { FastifyReply, FastifyRequest } from "fastify"
import type { PluginFastifyInstance } from "types"
import { Type } from "@sinclair/typebox"
import { userUpdateSchema } from "../user.schema"

const permissions = ["user.isAdmin"]

const ParamsSchema = Type.Object({
  _id: Type.String(),
})
type Params = Static<typeof ParamsSchema>

type UserBody = Static<typeof userUpdateSchema>

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

  const handler = async (
    req: FastifyRequest<{
      Params: Params
      Body: UserBody
    }>,
    reply: FastifyReply,
  ) => {
    try {
      const payloadWithUser = await userService.updateUser(
        fastify,
        req.requestParams,
        req.params._id,
        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: "dataUpdate",
      broadcastChannels: ["userUpdated"],
    },
    schema: {
      summary: "Update a user",
      description: "Update specific fields of a user profile",
      tags: ["core/user"],
      params: ParamsSchema,
      body: userUpdateSchema,
    },
  }
}
