// server/api/auth/session.get.ts
import type { SessionResponse } from '~/types/auth'

export default defineEventHandler(async (event) => {
  console.log('🔍 Session endpoint called');

  const sessionCookie = getCookie(event, 'user_session');
  console.log('🍪 Session cookie exists:', !!sessionCookie);

  if (!sessionCookie) {
    console.log('❌ No session cookie found');
    throw createError({
      statusCode: 401,
      statusMessage: 'No session cookie found',
    });
  }

  try {
    // Get session from store using session ID
    const { getSession } = await import('~/server/utils/sessionStore');
    const session = getSession(sessionCookie);
    
    if (!session) {
      console.log('❌ Session not found in store or expired');
      deleteCookie(event, 'user_session');
      throw createError({
        statusCode: 401,
        statusMessage: 'Session not found or expired',
      });
    }
    
    console.log('📋 Session retrieved from store successfully');
    
    // Parse token payloads on-demand from tokens
    let accessTokenPayload = null;
    let idTokenPayload = null;
    let refreshTokenPayload = null;
    
    try {
      if (session.accessToken) {
        const accessParts = session.accessToken.split('.');
        if (accessParts.length >= 2) {
          accessTokenPayload = JSON.parse(Buffer.from(accessParts[1], 'base64').toString());
        }
      }
      
      if (session.idToken) {
        const idParts = session.idToken.split('.');
        if (idParts.length >= 2) {
          idTokenPayload = JSON.parse(Buffer.from(idParts[1], 'base64').toString());
        }
      }

      if (session.refreshToken) {
        const refreshParts = session.refreshToken.split('.');
        if (refreshParts.length >= 2) {
          refreshTokenPayload = JSON.parse(Buffer.from(refreshParts[1], 'base64').toString());
        }
      }
    } catch (parseError) {
      console.warn('⚠️ Failed to parse token payloads:', parseError);
    }
    
    // Use dynamic expiration from refresh token if available
    if (refreshTokenPayload?.exp) {
      session.expiresAt = refreshTokenPayload.exp * 1000;
    }
    

    const isExpired = Date.now() > session.expiresAt;
    console.log('   Is Expired:', isExpired);

    // Check if the session has expired
    if (isExpired) {
      console.log('⏰ Session has expired, clearing cookie');
      deleteCookie(event, 'user_session');
      throw createError({
        statusCode: 401,
        statusMessage: 'Session expired',
      });
    }

    // Return the full session data (already includes parsed payloads)
    const sessionResponse: SessionResponse & { 
      idTokenPayload?: any
      accessTokenPayload?: any
      fullSessionObject?: any
      status?: string
      remainingSeconds?: number
      idToken?: string
      scope?: string
      createdAt?: number
    } = {
      success: true,
      // Basic User Info
      user: session.user,

      // Raw Tokens
      accessToken: session.accessToken,
      refreshToken: session.refreshToken,
      idToken: session.idToken,

      // Session Timestamps
      expiresAt: session.expiresAt,
      createdAt: session.createdAt,
      remainingSeconds: Math.max(0, Math.floor((session.expiresAt - Date.now()) / 1000)),

      // Parsed token payloads (parsed on-demand, not stored in cookie)
      idTokenPayload: idTokenPayload,
      accessTokenPayload: accessTokenPayload,
      
      // Full session for debugging
      fullSessionObject: session,
      
      // OAuth metadata
      scope: session.scope,
      status: session.status || 'authenticated',
    };

    console.log('✅ Session is valid, returning full session data');
    return sessionResponse;
  } catch (parseError: any) {
    console.error('❌ Failed to parse session cookie:', parseError);
    
    // Check if this is an old session ID format (not base64 JSON)
    if (parseError.message?.includes('Unexpected token') || parseError.message?.includes('JSON')) {
      console.log('🧹 Detected old session format, clearing cookie...');
      deleteCookie(event, 'user_session');
      throw createError({
        statusCode: 401,
        statusMessage: 'Old session format detected. Please login again.',
      });
    }
    
    // If parsing fails, the session is invalid
    deleteCookie(event, 'user_session');
    throw createError({
      statusCode: 401,
      statusMessage: 'Invalid session data',
    });
  }
});
