import { auth } from "@/auth";
import { hasReachedLimit } from "@/lib/usage";
import { getUserPlan } from "@/lib/stripe/access";
import { UpgradePrompt } from "@/components/dashboard/upgrade-prompt";
import { suggestNextPlan } from "@/config/plans";
import type { UsageFeature } from "@prisma/client";

/**
 * Server Component gate for consumption-based limits (AI generations,
 * product analyses this month). Distinct from PlanGate, which only checks
 * plan tier — this checks the user's actual usage against their plan's
 * monthly allowance. Suggests the next plan up as the fix, since usage
 * limits scale with plan tier rather than being a single on/off feature.
 */
export async function UsageGate({
  feature,
  featureLabel,
  children,
}: {
  feature: UsageFeature;
  featureLabel: string;
  children: React.ReactNode;
}) {
  const session = await auth();
  if (!session?.user?.id) return null;

  const [reachedLimit, access] = await Promise.all([
    hasReachedLimit(session.user.id, feature),
    getUserPlan(session.user.id),
  ]);

  if (reachedLimit) {
    const nextPlan = suggestNextPlan(access.plan);
    return <UpgradePrompt requiredPlan={nextPlan} currentPlan={access.plan} featureLabel={featureLabel} />;
  }

  return <>{children}</>;
}
