package output

import (
	"context"
	"sync"
)

// DummyBackend keeps track of the latest frame without writing anywhere. Useful for unit testing.
type DummyBackend struct {
	mu        sync.Mutex
	info      BackendInfo
	cfg       BackendConfig
	closed    bool
	total     uint64
	lastFrame CompositeFrame
}

// NewDummyBackend constructs a lean backend that records the last frame seen.
func NewDummyBackend(name string) *DummyBackend {
	return &DummyBackend{
		info: BackendInfo{
			Name:        name,
			Description: "in-memory dummy backend",
			Capabilities: BackendCapabilities{
				SupportsComposite:  true,
				FixedRate:          false,
				MaxSamplesPerWrite: 0,
			},
		},
	}
}

// Configure stores the config values.
func (db *DummyBackend) Configure(_ context.Context, cfg BackendConfig) error {
	db.mu.Lock()
	defer db.mu.Unlock()
	db.cfg = cfg
	return nil
}

// Write captures the most recent frame and updates the sample count.
func (db *DummyBackend) Write(_ context.Context, frame *CompositeFrame) (int, error) {
	db.mu.Lock()
	defer db.mu.Unlock()
	if frame == nil {
		return 0, nil
	}
	db.lastFrame = *frame
	db.total += uint64(len(frame.Samples))
	return len(frame.Samples), nil
}

// Flush is a no-op for the dummy backend.
func (db *DummyBackend) Flush(_ context.Context) error {
	return nil
}

// Close marks the backend unusable.
func (db *DummyBackend) Close(_ context.Context) error {
	db.mu.Lock()
	defer db.mu.Unlock()
	db.closed = true
	return nil
}

// Info returns the backend descriptors.
func (db *DummyBackend) Info() BackendInfo {
	db.mu.Lock()
	defer db.mu.Unlock()
	return db.info
}

// TotalSamples reports how many samples have been written.
func (db *DummyBackend) TotalSamples() uint64 {
	db.mu.Lock()
	defer db.mu.Unlock()
	return db.total
}

// LastFrame exposes a snapshot of the last frame written.
func (db *DummyBackend) LastFrame() CompositeFrame {
	db.mu.Lock()
	defer db.mu.Unlock()
	return db.lastFrame
}
