/**
 * Onboarding Page - Server Component
 * All data via Clerk + Convex. No Prisma.
 */

import { redirect } from "next/navigation";
import { convexQuery } from "@/lib/convex-client";
import type { Lang } from "@/lib/config";
import { calculateOnboardingStatus } from "@/lib/types/onboarding.types";
import type { OnboardingProgress } from "@/lib/types/onboarding.types";
import OnboardingWizard from "@/components/onboarding/OnboardingWizard";

interface OnboardingPageProps {
  params: { lang: Lang };
}

export default async function OnboardingPage({ params }: OnboardingPageProps) {
  const { lang } = params;

  // Get Clerk user
  let userEmail: string | undefined;
  try {
    const { currentUser } = await import("@clerk/nextjs/server");
    const clerkUser = await currentUser();
    userEmail = clerkUser?.emailAddresses[0]?.emailAddress?.toLowerCase();
  } catch {
    // Clerk unavailable
  }

  if (!userEmail) {
    redirect(
      `/${lang}/clerk-login?redirect_url=${encodeURIComponent(`/${lang}/dashboard/onboarding`)}`,
    );
  }

  // Look up user in Convex
  const convexUser = await convexQuery<Record<string, unknown>>(
    "auth/queries:getUserByEmail",
    { email: userEmail },
  );

  const userId = convexUser
    ? (convexUser.prismaId as string) ||
      (convexUser.appUserId as string) ||
      (convexUser._id as string)
    : undefined;

  if (!userId) {
    redirect(`/${lang}/dashboard`);
  }

  // Check if already onboarded
  if (convexUser?.onboardingComplete) {
    redirect(`/${lang}/dashboard?tab=overview`);
  }

  // Build progress object from Convex user data
  const progress: OnboardingProgress = {
    id: `progress_${userId}`,
    userId,
    welcomeCompleted: true,
    whatsappCompleted: (convexUser?.whatsappConnected as boolean) || false,
    voiceAgentCompleted: false,
    knowledgeBaseCompleted: false,
    workflowsCompleted: false,
    testingCompleted: false,
    completedAt: null,
    createdAt: new Date(),
    updatedAt: new Date(),
  };

  const status = calculateOnboardingStatus(progress);

  // Get package tier from subscription
  const sub = await convexQuery<Record<string, unknown>>(
    "billing/queries:getActiveSubscription",
    { userId },
  );
  const packageTier = (sub?.tierId as string) || "tier1";

  return (
    <OnboardingWizard
      lang={lang}
      initialProgress={progress}
      initialStatus={status}
      packageTier={packageTier}
    />
  );
}

export async function generateMetadata({ params }: OnboardingPageProps) {
  const { lang } = params;
  const isAr = lang === "ar";

  return {
    title: isAr ? "إعداد الحساب - ماويدي" : "Account Setup - Mawidi",
    description: isAr
      ? "أكمل إعداد حسابك في ماويدي"
      : "Complete your Mawidi account setup",
  };
}
