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

const permissions = ["user.isAdmin"]

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

  const handler = async (req: FastifyRequest<{}>, reply: FastifyReply) => {
    try {
      const payload = await projectService.readProjects(
        fastify,
        req.requestParams,
      )

      if (!payload) {
        return reply.code(204)
      }

      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 projects",
      tags: ["core/project"],
      params: {},
    },
  }
}
