// server/api/auth/session.patch.ts
export default defineEventHandler(async (event) => {
  console.log("🔄 Session update endpoint called");

  const sessionId = getCookie(event, "user_session");
  
  if (!sessionId) {
    console.log("❌ No session cookie found");
    throw createError({
      statusCode: 401,
      statusMessage: "No session cookie found",
    });
  }

  try {
    // Get the update data from request body
    const body = await readBody(event);
    const { accessToken, idToken, refreshToken, expiresAt } = body;

    // Validate that at least one token is provided
    if (!accessToken && !idToken && !refreshToken) {
      throw createError({
        statusCode: 400,
        statusMessage: "At least one token must be provided",
      });
    }

    // Get session store functions
    const { getSession, updateSession } = await import('~/server/utils/sessionStore');
    
    // Verify session exists
    const session = getSession(sessionId);
    if (!session) {
      console.log("❌ Session not found");
      deleteCookie(event, "user_session");
      throw createError({
        statusCode: 401,
        statusMessage: "Session not found or expired",
      });
    }

    // Prepare updates object
    const updates: any = {};
    if (accessToken) updates.accessToken = accessToken;
    if (idToken) updates.idToken = idToken;
    if (refreshToken) updates.refreshToken = refreshToken;
    if (expiresAt) updates.expiresAt = expiresAt;

    // Update the session
    const updated = updateSession(sessionId, updates);
    
    if (!updated) {
      throw createError({
        statusCode: 500,
        statusMessage: "Failed to update session",
      });
    }

    console.log("✅ Session updated successfully");
    return {
      success: true,
      message: "Session updated successfully",
    };
  } catch (error: any) {
    console.error("❌ Failed to update session:", error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || "Failed to update session",
    });
  }
});
