package store

import (
	"sort"
	"sync"
	"time"

	"code.cubecraftcreations.com/CubeCraft-Creations/Control-Center/go-backend/internal/models"
	"github.com/google/uuid"
)

// SessionStore provides thread-safe CRUD operations for sessions.
type SessionStore struct {
	mu       sync.RWMutex
	sessions map[string]models.Session // id -> session
}

// NewSessionStore returns an initialized SessionStore.
func NewSessionStore() *SessionStore {
	return &SessionStore{
		sessions: make(map[string]models.Session),
	}
}

// ListActive returns all sessions with status "running" or "streaming", newest first.
func (s *SessionStore) ListActive() []models.Session {
	s.mu.RLock()
	defer s.mu.RUnlock()

	result := make([]models.Session, 0)
	for _, sess := range s.sessions {
		if sess.Status == "running" || sess.Status == "streaming" {
			result = append(result, sess)
		}
	}
	sort.Slice(result, func(i, j int) bool {
		return result[i].LastActivityAt.After(result[j].LastActivityAt)
	})
	return result
}

// Create inserts a new session.
func (s *SessionStore) Create(sess models.Session) models.Session {
	s.mu.Lock()
	defer s.mu.Unlock()

	if sess.ID == "" {
		sess.ID = uuid.New().String()
	}
	if sess.StartedAt.IsZero() {
		sess.StartedAt = time.Now().UTC()
	}
	if sess.LastActivityAt.IsZero() {
		sess.LastActivityAt = sess.StartedAt
	}
	s.sessions[sess.ID] = sess
	return sess
}

// UpdateStatus updates the status and last-activity timestamp of a session.
func (s *SessionStore) UpdateStatus(id, status string) bool {
	s.mu.Lock()
	defer s.mu.Unlock()

	sess, ok := s.sessions[id]
	if !ok {
		return false
	}
	sess.Status = status
	sess.LastActivityAt = time.Now().UTC()
	s.sessions[id] = sess
	return true
}

// Count returns the total number of sessions.
func (s *SessionStore) Count() int {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return len(s.sessions)
}
