/**
 * Shared dashboard authentication helper.
 *
 * Resolves the current user from Clerk, NextAuth session, or OTP auth_token cookie
 * — in that priority order.
 * Used by all dashboard server-component pages to avoid duplicating auth fallback logic.
 */

import { cookies } from "next/headers";
import type { Session } from "next-auth";
import { auth } from "@/lib/auth";
import { verifySecureToken } from "@/lib/secure-tokens";
import { logger } from "@/lib/logger";

export interface DashboardUser {
  userId: string;
  email?: string;
  name?: string;
  session: Session | null;
}

/**
 * Resolve the authenticated user for any dashboard page.
 * Returns null if no valid authentication is found (caller should redirect to login).
 *
 * Auth priority:
 *   0. Clerk (primary)
 *   1. NextAuth session
 *   2. OTP auth_token cookie
 */
export async function getDashboardUser(): Promise<DashboardUser | null> {
  // 0. Clerk path — always active post-migration
  {
    try {
      // Dynamic import avoids bundling Clerk server code in client
      const { auth: clerkAuth } = await import("@clerk/nextjs/server");
      const { userId: clerkUserId } = await clerkAuth();

      if (clerkUserId) {
        const { bridgeClerkUser } = await import("./clerk-user-bridge");
        const bridged = await bridgeClerkUser(clerkUserId);

        if (bridged) {
          return {
            userId: bridged.id,
            email: bridged.email,
            name: bridged.name,
            session: null,
          };
        }

        // Clerk authenticated but no Prisma record yet (new user pre-sync)
        logger.warn(
          "Clerk user has no Prisma record, using Clerk ID as fallback",
          {
            clerkUserId,
          },
        );
        return { userId: clerkUserId, session: null };
      }
    } catch (error) {
      // Non-fatal: fall through to NextAuth
      logger.error("Clerk auth check failed in getDashboardUser", { error });
    }
  }

  // 1. Try NextAuth session first
  let session: Session | null = null;
  try {
    session = (await auth()) as Session | null;
  } catch (error) {
    logger.error("Dashboard auth() call failed", { error });
  }

  if (session?.user?.id) {
    return {
      userId: session.user.id,
      email: session.user.email || undefined,
      name: session.user.name || undefined,
      session,
    };
  }

  // 2. Fallback to OTP auth_token cookie
  const cookieStore = await cookies();
  const authToken = cookieStore.get("auth_token")?.value;

  if (authToken) {
    try {
      const tokenData = await verifySecureToken(authToken);
      if (tokenData) {
        return {
          userId: tokenData.userId as string,
          email: tokenData.email as string,
          name: tokenData.fullName as string,
          session: null,
        };
      }
      logger.warn(
        "Invalid or expired auth_token - signature verification failed",
      );
    } catch (error) {
      logger.error("Auth token verification failed", { error });
    }
  }

  return null;
}
