import { Types } from "mongoose";
import { connectDB } from "@/lib/db";
import { Order, Product, Vendor } from "@/models";
import { successResponse, notFoundResponse } from "@/lib/api/response";
import { NotFoundError } from "@/lib/api/errors";
import { rateLimitByUser } from "@/lib/api/rate-limit-middleware";
import { getSettings } from "@/models/settings.model";
import { isDefaultVendorRecord } from "@/lib/multi-vendor";
import { withApi } from "@/lib/api/handler";

/**
 * GET /api/admin/vendors/[id]/stats
 * On-demand commerce counts for the vendor detail header. The Vendor model has
 * no cached stats sub-document (unlike CustomerProfile), so counts are computed
 * here: products by `vendorId`, orders by `subOrders[].vendorId`.
 */
export const GET = withApi<{ id: string }>(
  { auth: "admin" },
  async ({ request, params, session }) => {
    await rateLimitByUser(
      request,
      session.user.id,
      "admin:vendors:stats",
      "lenient",
      session.user.role,
    );

    const { id } = params;
    if (!Types.ObjectId.isValid(id)) {
      return notFoundResponse("Vendor");
    }

    await connectDB();
    const settings = await getSettings();
    if (!settings.multiVendorMode?.enabled) throw new NotFoundError("Vendor");

    const vendor = await Vendor.findById(id)
      .select("isDefault slug totalSales commission")
      .lean();
    if (!vendor || isDefaultVendorRecord(vendor)) {
      return notFoundResponse("Vendor");
    }

    const vendorObjectId = new Types.ObjectId(id);
    const [productCount, orderCount] = await Promise.all([
      Product.countDocuments({ vendorId: vendorObjectId }),
      Order.countDocuments({ "subOrders.vendorId": vendorObjectId }),
    ]);

    return successResponse({
      productCount,
      orderCount,
      totalSales: vendor.totalSales ?? 0,
      commission: vendor.commission ?? 0,
    });
  },
);
