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

const BodySchema = Type.Object({
  collections: Type.Array(Type.String(), {
    description: "Array of collection names to drop",
    minItems: 1,
  }),
  dropAll: Type.Optional(
    Type.Boolean({
      description:
        "If true, drops all collections (overrides collections array)",
    }),
  ),
})
type Body = Static<typeof BodySchema>

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

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

      let result

      if (req.body.dropAll) {
        fastify.log.warn(
          `[API] Admin ${req.user._id} is dropping ALL collections`,
        )
        result = await collectionService.dropAllCollections(fastify)
      } else {
        fastify.log.warn(
          `[API] Admin ${req.user._id} is dropping collections: ${req.body.collections.join(", ")}`,
        )
        result = await collectionService.dropCollections(
          fastify,
          req.body.collections,
        )
      }

      return {
        success: true,
        dropped: result.dropped,
        failed: result.failed,
        message: `Successfully dropped ${result.dropped.length} collection(s)`,
      }
    } catch (error: any) {
      fastify.log.error(error.message)
      return reply.internalServerError(error.message)
    }
  }

  return {
    handler,
    onRequest: [fastify.authenticate],
    schema: {
      summary: "Drop collections",
      description:
        "Drop selected MongoDB collections (admin only, debug feature - USE WITH CAUTION)",
      tags: ["debug/collections"],
      body: BodySchema,
      response: {
        200: {
          type: "object",
          properties: {
            success: { type: "boolean" },
            dropped: {
              type: "array",
              items: { type: "string" },
            },
            failed: {
              type: "array",
              items: { type: "string" },
            },
            message: { type: "string" },
          },
        },
      },
    },
  }
}
