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

const permissions = ["user.isAdmin"]

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

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

  const handler = async (
    req: FastifyRequest<{
      Params: Params
    }>,
    reply: FastifyReply,
  ) => {
    try {
      const { _id } = req.params

      const payload = await accountService.readAccount(
        fastify,
        req.requestParams,
        _id,
      )

      if (!payload) {
        return reply.notFound("Account not found")
      }

      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: "dataRead",
    },
    schema: {
      summary: "Get an account by id",
      tags: ["core/account"],
      params: ParamsSchema,
    },
  }
}
