import type { Static } from "@sinclair/typebox"
import type { FastifyReply, FastifyRequest } from "fastify"
import { PluginFastifyInstance } from "types"
import { Type } from "@sinclair/typebox"
import { ForbiddenError } from "@/utils/errors"

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

const QuerySchema = Type.Object({
  account: Type.Optional(Type.String()),
})
type Query = Static<typeof QuerySchema>

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

  const handler = async (
    req: FastifyRequest<{
      Params: Params
      Querystring: Query
    }>,
    reply: FastifyReply,
  ) => {
    try {
      return await userService.readUser(
        fastify,
        req.requestParams,
        req.params._id,
      )
    } catch (error: any) {
      fastify.log.error(error.message)
      return reply.internalServerError(error.message)
    }
  }

  return {
    handler,
    onRequest: [fastify.authenticate],
    config: {
      type: "dataRead",
    },
    schema: {
      summary: "Get user",
      description: "Retrieve a single user by ID ",
      tags: ["core/user"],
      params: ParamsSchema,
      querystring: QuerySchema,
    },
  }
}
