package server

import (
	"fmt"
	"path/filepath"
	"sync"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestJobsStore(t *testing.T) {
	t.Run("AppendAndRead", func(t *testing.T) {
		path := filepath.Join(t.TempDir(), "jobs.jsonl")
		rs := []*jobRecord{
			{ID: "export-probe-1", Kind: jobExportProbe, StartedAt: "2026-08-11T10:00:00Z"},
			{ID: "export-probe-2", Kind: jobExportProbe, StartedAt: "2026-08-11T10:01:00Z"},
			{ID: "migrate-run-3", Kind: jobMigrateRun, StartedAt: "2026-08-11T10:02:00Z"},
		}
		for _, r := range rs {
			assert.NoError(t, appendJobRecord(path, r))
		}
		got, err := readJobRecords(path)
		assert.NoError(t, err)
		require.Len(t, got, 3)
		for i, want := range rs {
			assert.Equal(t, want.ID, got[i].ID)
		}
	})

	t.Run("EmptyFile", func(t *testing.T) {
		path := filepath.Join(t.TempDir(), "missing.jsonl")
		got, err := readJobRecords(path)
		assert.NoError(t, err)
		assert.NotNil(t, got, "got should be non-nil slice")
		assert.Empty(t, got, "got should be empty")
	})
}

func TestAppendJobRecordConcurrent(t *testing.T) {
	path := filepath.Join(t.TempDir(), "jobs.jsonl")
	var wg sync.WaitGroup
	for i := 0; i < 8; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			for j := 0; j < 10; j++ {
				rec := &jobRecord{
					ID:         fmt.Sprintf("migrate-run-%d-%d", i, j),
					Kind:       jobMigrateRun,
					StartedAt:  "2026-08-20T00:00:00Z",
					FinishedAt: "2026-08-20T00:00:01Z",
				}
				assert.NoError(t, appendJobRecord(path, rec))
			}
		}(i)
	}
	wg.Wait()
	got, err := readJobRecords(path)
	assert.NoError(t, err)
	assert.Len(t, got, 80, "every serialized append must survive")
}
