/**
 * Convex helper utilities for server-side operations
 *
 * Provides convenience wrappers around convex-client for common patterns
 * like ensuring a user exists before performing mutations.
 */

import {
  convexQuery,
  convexMutation,
  isConvexConfigured,
} from "./convex-client";
import { CONVEX_PATHS } from "./convex-paths";
import { logger } from "./logger";

interface ConvexUser {
  _id: string;
  email: string;
  name?: string | null;
  [key: string]: unknown;
}

/**
 * Ensure a user exists in Convex by email. Creates if missing.
 * Returns the Convex user record, or null if Convex is not configured.
 *
 * Non-throwing — callers should handle null gracefully.
 */
export async function ensureConvexUser(
  email: string,
  name?: string,
): Promise<ConvexUser | null> {
  if (!isConvexConfigured()) return null;

  // Look up existing user
  const existing = await convexQuery<ConvexUser>(CONVEX_PATHS.getUserByEmail, {
    email,
  });

  if (existing) return existing;

  // Create a new user in Convex
  logger.info("Creating Convex user", { email });
  const newId = await convexMutation<string>(CONVEX_PATHS.createUserNoAuth, {
    email,
    name: name ?? null,
  });

  if (!newId) return null;

  // Re-fetch to return full user object
  const created = await convexQuery<ConvexUser>(CONVEX_PATHS.getUserByEmail, {
    email,
  });

  return created;
}
