import type { FastifyReply, FastifyRequest } from "fastify"
import { PluginFastifyInstance } from "types"
import {
  workSessionCreateSchema,
  type WorkSessionCreate,
} from "../workSession.schema"

const permissions = ["user.isAdmin"]

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

  const handler = async (
    req: FastifyRequest<{
      Body: WorkSessionCreate
    }>,
    reply: FastifyReply,
  ) => {
    try {
      // Set userId from authenticated user if not provided
      const workSessionBody = {
        ...req.body,
        userId: req.body.userId || req.user?._id,
      }

      const payload = await workSessionService.createWorkSession(
        fastify,
        req.requestParams,
        workSessionBody,
      )

      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: ["workSessionCreated"],
    },
    schema: {
      summary: "Create a new workSession",
      tags: ["core/workSession"],

      body: workSessionCreateSchema,
    },
  }
}
