//go:build epics

package epics_test

import (
	"context"
	"os"
	"testing"
	"time"

	"github.com/uopi/uopi/internal/datasource"
	"github.com/uopi/uopi/internal/datasource/epics"
)

// TestIntegration_SubscribeAndMetadata is an integration test that requires:
//   - EPICS_BASE to be set in the environment (i.e. EPICS Base is installed).
//   - TEST_PV to name a readable EPICS PV accessible via Channel Access.
//
// It connects to the named PV, waits up to 5 seconds for at least one value
// update, and then verifies that the metadata contains a unit string.
func TestIntegration_SubscribeAndMetadata(t *testing.T) {
	if os.Getenv("EPICS_BASE") == "" {
		t.Skip("EPICS_BASE not set; skipping EPICS integration test")
	}
	pvName := os.Getenv("TEST_PV")
	if pvName == "" {
		t.Skip("TEST_PV not set; skipping EPICS integration test")
	}

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	ds := epics.New("", "") // rely on environment for CA addr list / EPICS_CA_ADDR_LIST
	if err := ds.Connect(ctx); err != nil {
		t.Fatalf("Connect: %v", err)
	}

	// Fetch metadata before subscribing so we exercise GetMetadata.
	meta, err := ds.GetMetadata(ctx, pvName)
	if err != nil {
		t.Fatalf("GetMetadata(%q): %v", pvName, err)
	}
	t.Logf("metadata: name=%q unit=%q type=%v displayLow=%v displayHigh=%v writable=%v",
		meta.Name, meta.Unit, meta.Type, meta.DisplayLow, meta.DisplayHigh, meta.Writable)

	// Subscribe and wait for at least one value update within 5 seconds.
	ch := make(chan datasource.Value, 8)
	cancelSub, err := ds.Subscribe(ctx, pvName, ch)
	if err != nil {
		t.Fatalf("Subscribe(%q): %v", pvName, err)
	}
	defer cancelSub()

	select {
	case v := <-ch:
		t.Logf("received value: ts=%v data=%v quality=%v", v.Timestamp, v.Data, v.Quality)
		if v.Quality == datasource.QualityBad {
			t.Errorf("expected QualityGood or QualityUncertain, got QualityBad")
		}
	case <-time.After(5 * time.Second):
		t.Fatal("timed out waiting for first value update from PV")
	case <-ctx.Done():
		t.Fatal("context expired before receiving a value")
	}

	// ListSignals should now return at least one entry (the one we just connected).
	signals, err := ds.ListSignals(ctx)
	if err != nil {
		t.Fatalf("ListSignals: %v", err)
	}
	if len(signals) == 0 {
		t.Error("ListSignals returned no signals after successful Subscribe")
	}

	// History should return ErrHistoryUnavailable when no archive URL is set.
	_, err = ds.History(ctx, pvName, time.Now().Add(-time.Hour), time.Now(), 100)
	if err != datasource.ErrHistoryUnavailable {
		t.Errorf("History with no archive URL: want ErrHistoryUnavailable, got %v", err)
	}
}
