package service

import (
	"sync"
	"time"
)

type UploadStatus struct {
	FileName   string    `json:"fileName"`
	Size       int64     `json:"size"`
	Progress   int       `json:"progress"`
	Status     string    `json:"status"`
	ObjectName string    `json:"objectName"`
	BucketName string    `json:"bucketName"`
	StartTime  time.Time `json:"startTime"`
	Error      string    `json:"error,omitempty"`
}

type UploadManager interface {
	Add(uploadID string, status *UploadStatus)
	UpdateProgress(uploadID string, progress int)
	UpdateStatus(uploadID string, status string, err error)
	Get(uploadID string) (*UploadStatus, bool)
}

type uploadManager struct {
	uploads map[string]*UploadStatus
	mutex   sync.RWMutex
}

func NewUploadManager() UploadManager {
	return &uploadManager{
		uploads: make(map[string]*UploadStatus),
	}
}

// Add menambahkan status upload baru
func (um *uploadManager) Add(uploadID string, status *UploadStatus) {
	um.mutex.Lock()
	defer um.mutex.Unlock()
	um.uploads[uploadID] = status
}

// UpdateProgress memperbarui progress upload
func (um *uploadManager) UpdateProgress(uploadID string, progress int) {
	um.mutex.Lock()
	defer um.mutex.Unlock()
	if status, exists := um.uploads[uploadID]; exists {
		status.Progress = progress
	}
}

// UpdateStatus memperbarui status upload
func (um *uploadManager) UpdateStatus(uploadID string, status string, err error) {
	um.mutex.Lock()
	defer um.mutex.Unlock()
	if upload, exists := um.uploads[uploadID]; exists {
		upload.Status = status
		if err != nil {
			upload.Error = err.Error()
		}
	}
}

// Get mendapatkan status upload berdasarkan ID
func (um *uploadManager) Get(uploadID string) (*UploadStatus, bool) {
	um.mutex.RLock()
	defer um.mutex.RUnlock()
	status, exists := um.uploads[uploadID]
	return status, exists
}
