package storage

import (
	"context"
	"time"

	"github.com/atlasos/calypso/internal/common/database"
	"github.com/atlasos/calypso/internal/common/logger"
)

// DiskMonitor handles periodic disk discovery and sync to database
type DiskMonitor struct {
	diskService *DiskService
	logger      *logger.Logger
	interval    time.Duration
	stopCh      chan struct{}
}

// NewDiskMonitor creates a new disk monitor service
func NewDiskMonitor(db *database.DB, log *logger.Logger, interval time.Duration) *DiskMonitor {
	return &DiskMonitor{
		diskService: NewDiskService(db, log),
		logger:      log,
		interval:    interval,
		stopCh:      make(chan struct{}),
	}
}

// Start starts the disk monitor background service
func (m *DiskMonitor) Start(ctx context.Context) {
	m.logger.Info("Starting disk monitor service", "interval", m.interval)
	ticker := time.NewTicker(m.interval)
	defer ticker.Stop()

	// Run initial sync immediately
	m.syncDisks(ctx)

	for {
		select {
		case <-ctx.Done():
			m.logger.Info("Disk monitor service stopped")
			return
		case <-m.stopCh:
			m.logger.Info("Disk monitor service stopped")
			return
		case <-ticker.C:
			m.syncDisks(ctx)
		}
	}
}

// Stop stops the disk monitor service
func (m *DiskMonitor) Stop() {
	close(m.stopCh)
}

// syncDisks performs disk discovery and sync to database
func (m *DiskMonitor) syncDisks(ctx context.Context) {
	m.logger.Debug("Running periodic disk sync")
	if err := m.diskService.SyncDisksToDatabase(ctx); err != nil {
		m.logger.Error("Periodic disk sync failed", "error", err)
	} else {
		m.logger.Debug("Periodic disk sync completed")
	}
}
