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 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<{
      Querystring: Query
    }>,
    reply: FastifyReply,
  ) => {
    try {
      //TODO rework this once we have permission system in place
      const filter: any = { isDeleted: req.query?.isDeleted || false }
      if (req.query.account) {
        filter.account = req.query.account
      }
      const payloads = await userService.readUsers(
        fastify,
        req.requestParams,
        filter,
      )
      return payloads
    } catch (error: any) {
      fastify.log.error(error.message)
      return reply.internalServerError(error.message)
    }
  }

  return {
    handler,
    onRequest: [fastify.authenticate],
    config: {
      type: "dataRead",
    },
    schema: {
      summary: "Get users",
      description: "Retrieve multiple users by filter criteria",
      tags: ["core/users"],
      querystring: QuerySchema,
    },
  }
}
