// server/api/users/sync.post.ts
// Auto-save/update user data when they first login
// This endpoint will be called automatically when user logs in

export default defineEventHandler(async (event) => {
  console.log("🔄 User sync endpoint called");

  const { getSessionFromCookie } = await import('~/server/utils/sessionStore');
  const session = await getSessionFromCookie(event);
  
  if (!session) {
    throw createError({
      statusCode: 401,
      statusMessage: "No session found or session expired",
    });
  }

  try {

    // Use the shared sync utility
    // Use session createdAt as loginTime, or current time if not available
    const { syncUserFromTokens } = await import('~/server/utils/userSync');
    const loginTime = session.createdAt || Date.now();
    
    console.log("🔄 Syncing user from session...");
    console.log("   Session createdAt:", session.createdAt);
    console.log("   Login time:", loginTime);
    
    const result = syncUserFromTokens(session.idToken, session.accessToken, loginTime);
    
    console.log(`✅ Sync result: ${result.action} - ${result.message}`);
    
    return result;
  } catch (error: any) {
    console.error("❌ Error syncing user:", error);
    throw createError({
      statusCode: 500,
      statusMessage: error.message || "Failed to sync user data",
    });
  }
});

