import type { FastifyReply, FastifyRequest } from "fastify"
import type { PluginFastifyInstance } from "types"

const permissions = ["user.isAdmin"]

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

  const handler = async (req: FastifyRequest, reply: FastifyReply) => {
    try {
      const payload = await accountService.readAccounts(
        fastify,
        req.requestParams,
      )

      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 all accounts. Only available to admins.",
      tags: ["core/account"],
      params: {},
    },
  }
}
