/**
 * Authentication Helpers
 * Clerk-backed helpers for API routes that still expect a single auth lookup.
 */

import { NextRequest } from "next/server";
import { auth } from "./auth";
import { prisma } from "./db";
import { logger } from "./logger";

/**
 * Get the authenticated database user from the current Clerk-backed session.
 */
export async function getAuthenticatedUser(_request: NextRequest) {
  try {
    void _request;
    const session = await auth();
    const sessionUser = session?.user;

    if (!sessionUser) {
      return null;
    }

    if (!sessionUser.id && !sessionUser.email) {
      return null;
    }

    const user = await prisma.users.findFirst({
      where:
        sessionUser.id && sessionUser.email
          ? {
              OR: [{ id: sessionUser.id }, { email: sessionUser.email }],
            }
          : sessionUser.id
            ? { id: sessionUser.id }
            : { email: sessionUser.email! },
    });

    if (user) {
      return { user, source: "clerk" as const };
    }

    return null;
  } catch (error) {
    logger.error("Authentication check failed", error);
    return null;
  }
}
