import type { FastifyReply, FastifyRequest } from "fastify"
import type { PluginFastifyInstance } from "types"
import { Type } from "@sinclair/typebox"

const permissions = ["user.isAdmin"]

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

  const handler = async (
    req: FastifyRequest<{
      Params: { projectId: string }
    }>,
    reply: FastifyReply,
  ) => {
    try {
      return await userService.updateLastProject(
        fastify,
        req.requestParams,
        req.user._id,
        req.params.projectId,
      )
    } catch (error: any) {
      fastify.log.error(error.message)
      return reply.internalServerError(error.message)
    }
  }

  return {
    handler,
    onRequest: [fastify.authenticate, fastify.checkPermissions(permissions)],
    config: {
      type: "dataUpdate",
      broadcastChannels: ["userUpdated"],
    },
    schema: {
      summary: "Set last accessed project for given user",
      description:
        "Takes the user in the provided token and writes the given project id into the user's UX config",
      tags: ["core/user"],
      params: Type.Object({
        projectId: Type.String(),
      }),
    },
  }
}
