package query

import (
	"sync"
	"time"

	"github.com/google/uuid"
)

// Job is a server-side query record.
type Job struct {
	ID                        string
	Provider                  string
	Region                    string
	EngineName                string
	ExecutionID               string
	SQL                       string
	EffectiveSQL              string
	Database                  string
	Dataset                   string
	OutputMode                string
	ClusterID                 string
	TenantID                  string
	GitHubUsername            string
	Status                    string
	Error                     string
	SubmittedAt               time.Time
	CompletedAt               *time.Time
	ScannedBytes              int64
	EngineExecutionTimeMillis int64
	TotalExecutionTimeMillis  int64
	QueryQueueTimeMillis      int64
	QueryPlanningTimeMillis   int64
	UsageLogged               bool // true after terminal usage log emitted (dedupe async polls)
}

type jobStore struct {
	mu   sync.RWMutex
	jobs map[string]*Job
}

func newJobStore() *jobStore {
	return &jobStore{jobs: map[string]*Job{}}
}

func (s *jobStore) create(job *Job) *Job {
	s.mu.Lock()
	defer s.mu.Unlock()
	if job.ID == "" {
		job.ID = uuid.NewString()
	}
	cp := *job
	s.jobs[cp.ID] = &cp
	return &cp
}

func (s *jobStore) get(id string) (*Job, bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	j, ok := s.jobs[id]
	if !ok {
		return nil, false
	}
	cp := *j
	return &cp, true
}

func (s *jobStore) update(id string, fn func(*Job)) (*Job, bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	j, ok := s.jobs[id]
	if !ok {
		return nil, false
	}
	fn(j)
	cp := *j
	return &cp, true
}
