import { getSessionForSSR } from "supertokens-node/custom";
import { ensureSuperTokensBackend } from "../server";
import { logger } from "../";
import SuperTokens from "supertokens-node";

export async function getSessionForStart(request: Request, options?: { sessionRequired?: boolean }) {
  ensureSuperTokensBackend();
  try {
    const session = await getSessionForSSR(request);
    
    if (session.hasToken) {
      const userId = session.accessTokenPayload?.sub;
      if (userId === undefined || session.accessTokenPayload?.sessionHandle === undefined) {
        return { 
          hasToken: true,
          needsRefresh: true,
          error: 'TRY_REFRESH_TOKEN'
        }
      }
      
      const user = await SuperTokens.getUser(userId);


      return {
        hasToken: true,
        accessTokenPayload: session.accessTokenPayload,
        userId,
        sessionHandle: session.accessTokenPayload?.sessionHandle,
        phone: user?.phoneNumbers[0]
      };
    }
    
    return null;
  } catch (error: any) {
    logger.error("Session error", error);
    
    if (error.type === "TRY_REFRESH_TOKEN") {
      return {
        hasToken: false,
        needsRefresh: true,
        error: 'TRY_REFRESH_TOKEN'
      };
    }
    
    if (options?.sessionRequired === false) {
      return null;
    }
    
    throw error;
  }
}
