import type { FastifyReply, FastifyRequest, FastifyInstance } from "fastify"
import { authenticate } from "@m/authentication"
import { callDataTypeOperation } from "@c/contracting/contractRegistrar"

export default (fastify: FastifyInstance) => {
  const checkDatabase = async () => {
    const userCount = await callDataTypeOperation(
      "raclette__core",
      "user",
      "readCount",
    )

    return userCount > 0
  }

  const handler = async (req: FastifyRequest, reply: FastifyReply) => {
    if (!(await checkDatabase())) {
      // user database is empty
      // this is a critical information for the frontend
      const replyObj = {
        statusCode: 500,
        code: "RCLT_DB_NO_USERS",
        error: "NoUsersInDatabase",
        message: "No Users in Database",
      }

      return reply.code(replyObj.statusCode).send(replyObj)
    }
    await authenticate(req, reply, fastify)

    // Only send success response if reply hasn't been sent yet
    if (!reply.sent) {
      return reply.send(req.user)
    }
  }

  return {
    handler: handler,
    skipHeaderValidation: true,
    schema: {
      summary: "Get a single user.",
      description: `Retrieve a single user, e.g. to edit the object. Only
    administrators, project maintainers and the user himself/herself can access
    this object directly.`,
      tags: ["core/user"],
      params: {},
    },
  }
}
