package store

import (
	"sort"
	"sync"
	"time"

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

// TaskStore provides thread-safe CRUD operations for tasks.
type TaskStore struct {
	mu    sync.RWMutex
	tasks map[string]models.Task
}

// NewTaskStore returns an initialized TaskStore.
func NewTaskStore() *TaskStore {
	return &TaskStore{
		tasks: make(map[string]models.Task),
	}
}

// ListRecent returns tasks ordered by updated_at descending (newest first).
func (s *TaskStore) ListRecent() []models.Task {
	s.mu.RLock()
	defer s.mu.RUnlock()

	result := make([]models.Task, 0, len(s.tasks))
	for _, t := range s.tasks {
		result = append(result, t)
	}
	sort.Slice(result, func(i, j int) bool {
		return result[i].UpdatedAt.After(result[j].UpdatedAt)
	})
	return result
}

// Create inserts a new task.
func (s *TaskStore) Create(t models.Task) models.Task {
	s.mu.Lock()
	defer s.mu.Unlock()

	if t.ID == "" {
		t.ID = uuid.New().String()
	}
	now := time.Now().UTC()
	if t.CreatedAt.IsZero() {
		t.CreatedAt = now
	}
	if t.UpdatedAt.IsZero() {
		t.UpdatedAt = now
	}
	s.tasks[t.ID] = t
	return t
}

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