import { Injectable } from '@nestjs/common';
import { SessionRepository } from '../../infrastructure/repositories/session.repository';
import { AgentSession } from '../entities/agent-session.entity';
import * as crypto from 'crypto';

@Injectable()
export class SessionManager {
  constructor(private readonly sessionRepo: SessionRepository) {}

  async createSession(tenantId: string, userId?: string): Promise<AgentSession> {
    const session = new AgentSession();
    session.id = crypto.randomUUID();
    session.tenantId = tenantId;
    session.engineType = '';
    session.status = 'active';
    session.metadata = {};
    session.createdAt = new Date();
    session.updatedAt = new Date();
    return this.sessionRepo.save(session);
  }

  async getSession(sessionId: string): Promise<AgentSession | null> {
    return this.sessionRepo.findById(sessionId);
  }

  async endSession(sessionId: string): Promise<void> {
    const session = await this.sessionRepo.findById(sessionId);
    if (session) {
      session.status = 'completed';
      session.updatedAt = new Date();
      await this.sessionRepo.save(session);
    }
  }

  async getActiveSessions(): Promise<AgentSession[]> {
    return this.sessionRepo.findByStatus('active');
  }
}
