import type { FastifyReply, FastifyRequest } from "fastify"
import { PluginFastifyInstance } from "types"
import { ForbiddenError } from "@/utils/errors"

export default (fastify: PluginFastifyInstance) => {
  const collectionService = fastify.core.collectionService

  const handler = async (req: FastifyRequest, reply: FastifyReply) => {
    try {
      // Restrict to admin users only
      if (!req.user.isAdmin) {
        throw new ForbiddenError(
          "Only Admins can access collection information",
        )
      }

      const collections = await collectionService.getCollections(fastify)

      return {
        success: true,
        data: collections,
        total: collections.length,
      }
    } catch (error: any) {
      fastify.log.error(error.message)
      return reply.internalServerError(error.message)
    }
  }

  return {
    handler,
    onRequest: [fastify.authenticate],
    schema: {
      summary: "Get all collections",
      description:
        "Retrieve all MongoDB collections with metadata (admin only, debug feature)",
      tags: ["debug/collections"],
      response: {
        200: {
          type: "object",
          properties: {
            success: { type: "boolean" },
            data: {
              type: "array",
              items: {
                type: "object",
                properties: {
                  name: { type: "string" },
                  count: { type: "number" },
                  size: { type: "number" },
                  indexes: { type: "number" },
                },
              },
            },
            total: { type: "number" },
          },
        },
      },
    },
  }
}
