import { auth } from "@/auth";
import { canUseFeature, getUserPlan } from "@/lib/stripe/access";
import { UpgradePrompt } from "@/components/dashboard/upgrade-prompt";
import type { PlanCode } from "@prisma/client";

/**
 * Server Component gate for plan-tier features. This is the enforcement
 * layer — it re-checks access on the server regardless of what the client
 * rendered, so a feature is never reachable just because a button was
 * hidden. Wrap the real feature UI in this; on failure it renders
 * UpgradePrompt instead of `children`.
 */
export async function PlanGate({
  requiredPlan,
  featureLabel,
  children,
}: {
  requiredPlan: PlanCode;
  featureLabel: string;
  children: React.ReactNode;
}) {
  const session = await auth();
  if (!session?.user?.id) return null;

  const [allowed, access] = await Promise.all([
    canUseFeature(session.user.id, requiredPlan),
    getUserPlan(session.user.id),
  ]);

  if (!allowed) {
    return (
      <UpgradePrompt requiredPlan={requiredPlan} currentPlan={access.plan} featureLabel={featureLabel} />
    );
  }

  return <>{children}</>;
}
