import type { FastifyReply, FastifyRequest } from "fastify"
import type { PluginFastifyInstance } from "types"
import { projectCreateSchema, type ProjectCreate } from "../project.schema"

const permissions = ["user.isAdmin"]

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

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

      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: "dataCreate",
      broadcastChannels: ["projectCreated"],
    },
    schema: {
      summary: "Create a new project",
      tags: ["core/project"],

      body: projectCreateSchema,
    },
  }
}
