/**
 * Clerk Auth Helpers — Strangler Fig Migration Layer
 *
 * These helpers mirror the NextAuth session interface so call sites
 * can switch between auth providers via DS_AUTH=convex env var.
 *
 * Only active when NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY is set.
 * All functions return null gracefully when Clerk is not configured.
 */

import { auth, currentUser } from "@clerk/nextjs/server";

export interface ClerkAuthUser {
  id: string;
  email: string | null;
  name: string | null;
  imageUrl: string | null;
}

const isClerkConfigured = () =>
  Boolean(process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY);

/**
 * Get current Clerk user (server-side).
 * Returns null if not authenticated or Clerk is not configured.
 */
export async function getClerkUser(): Promise<ClerkAuthUser | null> {
  if (!isClerkConfigured()) return null;

  try {
    const user = await currentUser();
    if (!user) return null;

    const primaryEmail = user.emailAddresses.find(
      (e) => e.id === user.primaryEmailAddressId,
    );

    return {
      id: user.id,
      email: primaryEmail?.emailAddress ?? null,
      name: user.fullName ?? user.firstName ?? null,
      imageUrl: user.imageUrl ?? null,
    };
  } catch {
    return null;
  }
}

/**
 * Require Clerk authentication — throws if not authenticated.
 * Use in protected API routes when DS_AUTH=convex.
 */
export async function requireClerkAuth(): Promise<ClerkAuthUser> {
  const { userId } = await auth();

  if (!userId) {
    throw new Error("CLERK_UNAUTHENTICATED");
  }

  const user = await getClerkUser();
  if (!user) {
    throw new Error("CLERK_USER_NOT_FOUND");
  }

  return user;
}

/**
 * Get current Clerk user ID without fetching full user object.
 * Lightweight auth check for server components and API routes.
 */
export async function getClerkUserId(): Promise<string | null> {
  if (!isClerkConfigured()) return null;

  try {
    const { userId } = await auth();
    return userId;
  } catch {
    return null;
  }
}
