/**
 * Billing Panel Server Component
 *
 * Server-side wrapper that pre-fetches user data via Clerk + Convex.
 * No Prisma.
 */

import { convexQuery } from "@/lib/convex-client";
import BillingPanelClient from "./BillingPanelClient";
import type { Lang } from "@/lib/config";
import type { DashboardSubscriptionDetails } from "../types";
import type { Currency } from "@/lib/types/pricing";

export interface BillingPanelServerProps {
  lang: Lang;
  subscriptionDetails: DashboardSubscriptionDetails | null;
  billingCurrency: Currency;
  onUpgradeSuccess: () => void;
}

export default async function BillingPanelServer({
  lang,
  subscriptionDetails,
  billingCurrency,
  onUpgradeSuccess,
}: BillingPanelServerProps) {
  let initialUserData: {
    id: string;
    email: string;
    companyName?: string | null;
    goals?: string[] | null;
  } | null = null;

  try {
    const { currentUser } = await import("@clerk/nextjs/server");
    const clerkUser = await currentUser();
    const email = clerkUser?.emailAddresses[0]?.emailAddress?.toLowerCase();

    if (email) {
      const convexUser = await convexQuery<Record<string, unknown>>(
        "auth/queries:getUserByEmail",
        { email },
      );
      if (convexUser) {
        initialUserData = {
          id: (convexUser.prismaId as string) || (convexUser._id as string),
          email: convexUser.email as string,
          companyName: (convexUser.companyName as string) || null,
          goals: null,
        };
      }
    }
  } catch {
    // Auth unavailable — render without pre-fetched data
  }

  return (
    <BillingPanelClient
      lang={lang}
      subscriptionDetails={subscriptionDetails}
      billingCurrency={billingCurrency}
      onUpgradeSuccess={onUpgradeSuccess}
      initialUserData={initialUserData}
    />
  );
}
