/**
 * QM Session Actions - Session management and creation
 */

import { BaseHandler } from '@stock-bot/core/handlers';
import { QM_SESSION_IDS, SESSION_CONFIG } from '../shared/config';
import { QMSessionManager } from '../shared/session-manager';

/**
 * Check existing sessions and queue creation jobs for needed sessions
 */
export async function checkSessions(handler: BaseHandler): Promise<{
  cleaned: number;
  queued: number;
  message: string;
}> {
  const sessionManager = QMSessionManager.getInstance();
  const cleanedCount = sessionManager.cleanupFailedSessions();
  // Check which session IDs need more sessions and queue creation jobs
  let queuedCount = 0;
  for (const [sessionType, sessionId] of Object.entries(QM_SESSION_IDS)) {
    handler.logger.debug(`Checking session ID: ${sessionId}`);
    if (sessionManager.needsMoreSessions(sessionId)) {
      const currentCount = sessionManager.getSessions(sessionId).length;
      const neededSessions = SESSION_CONFIG.MAX_SESSIONS - currentCount;
      for (let i = 0; i < neededSessions; i++) {
        await handler.scheduleOperation('create-session', { sessionId, sessionType });
        handler.logger.info(`Queued job to create session for ${sessionType}`);
        queuedCount++;
      }
    }
  }

  return {
    cleaned: cleanedCount,
    queued: queuedCount,
    message: `Session check completed: cleaned ${cleanedCount}, queued ${queuedCount}`,
  };
}

/**
 * Create a single session for a specific session ID
 */
export async function createSingleSession(
  handler: BaseHandler,
  input: any
): Promise<{ sessionId: string; status: string; sessionType: string }> {
  const { sessionId: _sessionId, sessionType } = input || {};
  const _sessionManager = QMSessionManager.getInstance();

  // Get proxy from proxy service
  const _proxyString = handler.proxy.getProxy();

  // const session = {
  //   proxy: proxyString || 'http://proxy:8080',
  //   headers: sessionManager.getQmHeaders(),
  //   successfulCalls: 0,
  //   failedCalls: 0,
  //   lastUsed: new Date()
  // };

  handler.logger.info(`Creating session for ${sessionType}`);

  // Add session to manager
  // sessionManager.addSession(sessionType, session);

  return {
    sessionId: sessionType,
    status: 'created',
    sessionType,
  };
}
