/**
 * Workflow Management Dashboard Page - SERVER COMPONENT
 *
 * All data via Clerk + Convex. No Prisma.
 */

import { redirect } from "next/navigation";
import { convexQuery } from "@/lib/convex-client";
import { WorkflowManagementClient } from "./WorkflowManagementClient";
import type { Lang } from "@/lib/config";

export const dynamic = "force-dynamic";
export const revalidate = 0;

export const metadata = {
  title: "Workflow Management | Mawidi Dashboard",
  description: "Manage your AI agents, integrations, and automation workflows",
};

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

export default async function WorkflowsPage({ params }: WorkflowsPageProps) {
  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/workflows`)}`,
    );
  }

  // 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`);
  }

  // Get subscription
  const sub = await convexQuery<Record<string, unknown>>(
    "billing/queries:getActiveSubscription",
    { userId },
  );

  const packageTier = (sub?.tierId as string) || "tier1";

  return (
    <WorkflowManagementClient
      lang={lang}
      userId={userId}
      packageTier={packageTier}
    />
  );
}
