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 permissions = ["user.isAdmin"]

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

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

  const handler = async (
    req: FastifyRequest<{
      Params: Params
    }>,
    reply: FastifyReply,
  ) => {
    try {
      if (req.user._id === req.params._id) {
        throw new ForbiddenError("A user cannot remove itself")
      }

      const payloadWithUser = await userService.removeUser(
        fastify,
        req.requestParams,
        req.params._id,
      )

      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: "dataDelete",
      broadcastChannels: ["userDeleted"],
    },
    schema: {
      summary: "Delete a user",
      description:
        "Soft delete a user (marks as deleted but preserves the record)",
      tags: ["core/user"],
      params: ParamsSchema,
    },
  }
}
