import { createServerClient } from '@/shared/db/supabase-client';

// --- ASA GENERATED START ---
// Server-side user helpers.
// Security: ALL functions use getUser() for verified identity — NOT getSession().
// --- ASA GENERATED END ---

// --- USER CODE START ---

/**
 * Get the current authenticated user (server-side, verified).
 * Returns null if not authenticated.
 *
 * IMPORTANT: This uses getUser() which verifies the JWT against Supabase Auth server.
 * Do NOT use getSession() for security-sensitive operations — it reads unverified JWT from cookies.
 */
export async function getCurrentUser() {
  const supabase = createServerClient();
  const { data: { user }, error } = await supabase.auth.getUser();

  if (error || !user) {
    return null;
  }

  return {
    id: user.id,
    email: user.email ?? '',
  };
}

/**
 * Get the current user or throw.
 * Use in server actions / route handlers where auth is required.
 */
export async function requireUser() {
  const user = await getCurrentUser();
  if (!user) {
    throw new Error('Authentication required');
  }
  return user;
}

/**
 * Get user profile from profiles table.
 * Returns null if not found.
 */
export async function getUserProfile(userId: string) {
  const supabase = createServerClient();
  const { data, error } = await supabase
    .from('profiles')
    .select('id, display_name, role, created_at, updated_at')
    .eq('id', userId)
    .single();

  if (error) {
    return null;
  }
  return data;
}

// --- USER CODE END ---
