import { headers } from 'next/headers';
import { eq } from 'drizzle-orm';

import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { userProfiles, type UserPreferences } from '@/lib/db/schema/users';
import { DashboardShell } from '@/components/dashboard/dashboard-shell';

/**
 * Prefetch the user's first name + dashboard widget visibility server-side so
 * the dashboard renders its first paint with the rep's name and saved layout
 * already populated. Without this prefetch the page flickered three times on
 * cold cache: SSR fallback → /me arrives (firstName lands) → /preferences
 * arrives (widget layout reflows). All three caches are seeded synchronously
 * from the same DB row so the post-mount useQuery resolves instantly.
 */
export default async function DashboardPage() {
  // Resolve the signed-in user from the session cookie. The (dashboard)
  // layout already gates unauthenticated access; this is the second-pass
  // lookup that gives us the profile row.
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session?.user) {
    // The outer layout will redirect; bail with the un-prefetched shell so
    // we don't crash if this server component is invoked in a non-auth
    // context (e.g. a future preview / RSC sub-route).
    return <DashboardShell />;
  }

  const profile = await db.query.userProfiles.findFirst({
    where: eq(userProfiles.userId, session.user.id),
    columns: {
      firstName: true,
      preferences: true,
    },
  });

  const prefs = (profile?.preferences ?? {}) as UserPreferences;

  return (
    <DashboardShell
      initialFirstName={profile?.firstName ?? null}
      initialWidgetVisibility={prefs.dashboardWidgets ?? null}
    />
  );
}
