package service

import (
	"context"
	"testing"

	fmreport "wucher/internal/domain/fm_report"
	"wucher/internal/shared/pkg/uuidv7"
)

type fmSnapshotBuilderStub struct {
	built *fmreport.FleetHistory
	calls int
}

func (b *fmSnapshotBuilderStub) BuildFleetHistory(context.Context, []byte) *fmreport.FleetHistory {
	b.calls++
	return b.built
}

// TestFMReportCompleteFreezesFleetSnapshot verifies the fleet-status snapshot is written at
// COMPLETION (so the FM report shows live fleet status while open, frozen once completed).
func TestFMReportCompleteFreezesFleetSnapshot(t *testing.T) {
	flightID := uuidv7.MustBytes()
	reportID := uuidv7.MustBytes()
	takeoverID := uuidv7.MustBytes()

	var created *fmreport.FleetHistory
	repo := &fmReportRepoMock{
		getByFlightFn: func(context.Context, []byte) (*fmreport.Report, error) {
			return &fmreport.Report{ID: reportID, FlightID: flightID, TakeoverID: takeoverID, FlightInspectionID: uuidv7.MustBytes()}, nil
		},
		upsertFn:          func(context.Context, *fmreport.Report) error { return nil },
		getFleetHistoryFn: func(context.Context, []byte) (*fmreport.FleetHistory, error) { return nil, nil },
		createFleetHistoryFn: func(_ context.Context, row *fmreport.FleetHistory) error {
			created = row
			return nil
		},
	}
	builder := &fmSnapshotBuilderStub{built: &fmreport.FleetHistory{}}
	svc := NewFMReportService(repo).WithFleetHistoryBuilder(builder)

	if _, err := svc.Complete(context.Background(), flightID); err != nil {
		t.Fatalf("complete: %v", err)
	}
	if builder.calls != 1 {
		t.Fatalf("expected snapshot built once at completion, got %d", builder.calls)
	}
	if created == nil || string(created.FMReportID) != string(reportID) {
		t.Fatalf("expected snapshot created for the report at completion, got %+v", created)
	}
}
