package sync

import (
	"context"
	"log"
	"time"

	"tps.local/labbridge-agent/internal/queue"
)

// Heartbeat pings the cloud every interval seconds with the current queue
// depth. Failures are logged but never crash the loop — the cloud's Device
// Monitor will simply show the agent as offline until the next successful
// ping.
type Heartbeat struct {
	store    *queue.Store
	client   *Client
	interval time.Duration
}

func NewHeartbeat(store *queue.Store, client *Client, interval time.Duration) *Heartbeat {
	return &Heartbeat{store: store, client: client, interval: interval}
}

func (h *Heartbeat) Run(ctx context.Context) {
	h.ping()
	t := time.NewTicker(h.interval)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-t.C:
			h.ping()
		}
	}
}

func (h *Heartbeat) ping() {
	depth, _ := h.store.PendingCount()
	if err := h.client.Heartbeat(depth); err != nil {
		log.Printf("heartbeat: %v", err)
	}
}
