export default defineEventHandler(async (event) => {
  const parseJwtPayload = (token: string): { exp?: number } | null => {
    try {
      const payload = token.split('.')[1];
      if (!payload) return null;

      const decoded = Buffer.from(payload, 'base64').toString();
      return JSON.parse(decoded) as { exp?: number };
    } catch {
      return null;
    }
  };

  const sessionId = getCookie(event, "user_session");

  if (!sessionId) {
    throw createError({
      statusCode: 401,
      statusMessage: "No session cookie found",
    });
  }

   try {
    // Get session from server-side store using session ID
    const { getUserSession, deleteUserSession } = await import('~/server/utils/sessionStore');
    const session = getUserSession(sessionId);
    
    if (!session) {
      throw createError({
        statusCode: 401,
        statusMessage: "Session expired or invalid",
      });
    }

    const accessPayload = parseJwtPayload(session.accessToken);
    const nowInSeconds = Math.floor(Date.now() / 1000);

    if (!accessPayload?.exp || accessPayload.exp <= nowInSeconds) {
      deleteUserSession(sessionId);
      throw createError({
        statusCode: 401,
        statusMessage: "Access token expired or invalid",
      });
    }

    return {
      ...session, 
      payloadIdToken : session.idToken ? parseJwtPayload(session.idToken) : null,
      payloadAccessToken: accessPayload 
    };
  } catch (error: any) {
    if (error?.statusCode) {
      throw error;
    }

    console.error("❌ Failed to validate session:", error);
    throw createError({
      statusCode: 401,
      statusMessage: "Invalid session data",
    });
  }
});