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

type UserBody = Static<typeof userUpdateSchema>

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

  const handler = async (
    req: FastifyRequest<{
      Params: {}
      Body: UserBody
    }>,
    reply: FastifyReply,
  ) => {
    try {
      if (req.user._id !== req.body._id) {
        throw new UnauthorizedError("not your user")
      }
      // only let the user update non vital fields
      const updateObject = {}
      if (req.body?.email?.length) {
        updateObject.email = req.body.email
        // TODO Creation of the field should be happening in the user.model pre save hook
        // updateObject.email_verified = false
      }
      if (req.body?.firstname?.length) {
        updateObject.firstname = req.body.firstname
      }
      if (req.body?.lastname?.length) {
        updateObject.lastname = req.body.lastname
      }
      if (req.body?.password?.length) {
        updateObject.password = req.body.password
      }
      const payloadWithUser = await userService.updateUser(
        fastify,
        req.requestParams,
        req.user._id,
        updateObject,
      )

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

  return {
    handler,
    onRequest: [fastify.authenticate],
    config: {
      type: "dataUpdate",
      broadcastChannels: ["userUpdated"],
    },
    schema: {
      summary: "Update a user",
      description: "Update specific fields of a user profile",
      tags: ["core/user"],
      body: userUpdateSchema,
    },
  }
}
