package web

import (
	"fmt"
	"sync"
	"time"
)

type Session struct {
	ID         string
	MethodID   string
	Status     string
	Progress   float64
	OutputChan chan string
	ErrorChan  chan error
	DoneChan   chan struct{}
	CreatedAt  time.Time
}

type SessionManager struct {
	sessions map[string]*Session
	mux      sync.RWMutex
}

func NewSessionManager() *SessionManager {
	return &SessionManager{
		sessions: make(map[string]*Session),
	}
}

func (sm *SessionManager) Create(methodID string) *Session {
	sessionID := fmt.Sprintf("%d", time.Now().UnixNano())
	session := &Session{
		ID:         sessionID,
		MethodID:   methodID,
		Status:     "pending",
		OutputChan: make(chan string, 1000),
		ErrorChan:  make(chan error, 10),
		DoneChan:   make(chan struct{}),
		CreatedAt:  time.Now(),
	}

	sm.mux.Lock()
	sm.sessions[sessionID] = session
	sm.mux.Unlock()

	return session
}

func (sm *SessionManager) Get(sessionID string) (*Session, bool) {
	sm.mux.RLock()
	defer sm.mux.RUnlock()

	session, exists := sm.sessions[sessionID]
	return session, exists
}

func (sm *SessionManager) Cleanup(sessionID string) {
	sm.mux.Lock()
	defer sm.mux.Unlock()

	if session, exists := sm.sessions[sessionID]; exists {
		close(session.OutputChan)
		close(session.ErrorChan)
		close(session.DoneChan)
		delete(sm.sessions, sessionID)
	}
}
