package store

import (
	"sort"
	"sync"
	"time"

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

// ProjectStore provides thread-safe CRUD operations for projects.
type ProjectStore struct {
	mu       sync.RWMutex
	projects map[string]models.Project
}

// NewProjectStore returns an initialized ProjectStore.
func NewProjectStore() *ProjectStore {
	return &ProjectStore{
		projects: make(map[string]models.Project),
	}
}

// List returns all projects ordered by name.
func (s *ProjectStore) List() []models.Project {
	s.mu.RLock()
	defer s.mu.RUnlock()

	result := make([]models.Project, 0, len(s.projects))
	for _, p := range s.projects {
		result = append(result, p)
	}
	sort.Slice(result, func(i, j int) bool {
		return result[i].Name < result[j].Name
	})
	return result
}

// Create inserts a new project.
func (s *ProjectStore) Create(p models.Project) models.Project {
	s.mu.Lock()
	defer s.mu.Unlock()

	if p.ID == "" {
		p.ID = uuid.New().String()
	}
	now := time.Now().UTC()
	if p.CreatedAt.IsZero() {
		p.CreatedAt = now
	}
	if p.UpdatedAt.IsZero() {
		p.UpdatedAt = now
	}
	if p.AgentIDs == nil {
		p.AgentIDs = []string{}
	}
	s.projects[p.ID] = p
	return p
}

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