import { redirect } from "next/navigation";
import { asc, eq } from "drizzle-orm";

import { auth } from "@/lib/auth";
import { db } from "@tasks/database/client";
import { workspaceMembers, workspaces } from "@tasks/database/schema";

/**
 * Root landing route. Decides where an authenticated user goes when they
 * hit `/`. The post-sign-in `callbackUrl` defaults here, so this is the
 * single source of truth for "where does a user actually land?"
 *
 * Decision: land on the user's oldest workspace home (`/{slug}/`). Why oldest:
 * we don't have a "last visited" column yet (deliberately deferred — see
 * Task-pick-workspace-landing-route) and oldest-membership is stable across
 * page loads. The workspace home is no longer a mockup; it now shows real
 * stats and recent activity via `objects.stats` / `objects.listRecent`.
 *
 * The auth callback (`ensureUserHasWorkspace` in `apps/web/lib/auth.ts`)
 * provisions a personal workspace on first sign-in, so the zero-workspace
 * branch below should be effectively unreachable for fresh sign-ins. It
 * survives only as a defensive fallback for sessions that were minted
 * before that provisioning logic existed.
 */
export default async function HomePage() {
  const session = await auth();

  if (!session?.user?.id) {
    redirect("/sign-in");
  }

  const [membership] = await db
    .select({ slug: workspaces.slug })
    .from(workspaceMembers)
    .innerJoin(workspaces, eq(workspaces.id, workspaceMembers.workspaceId))
    .where(eq(workspaceMembers.userId, session.user.id))
    .orderBy(asc(workspaceMembers.createdAt))
    .limit(1);

  if (membership?.slug) {
    redirect(`/${membership.slug}`);
  }

  // Zero-workspace fallback. See header doc — this should be unreachable
  // post-`ensureUserHasWorkspace`. If we hit it anyway, bounce through
  // sign-in so the auth callback re-runs and provisions a workspace.
  // Track follow-up: a proper onboarding flow for users in this state
  // is captured in Plan-daily-driver-finish/Epic-shipping-the-shell/
  // Task-onboarding-zero-workspace-flow.md.
  redirect("/sign-in?error=no_workspace");
}
