package mysql

import (
	"context"
	"fmt"
	"testing"
	"time"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"

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

// TestFMReportUpdatePersistsEngineFields drives the repo Upsert path used by
// PATCH /fm-reports/update with the exact (correct) engine field names and asserts they
// persist through a read-back.
func TestFMReportUpdatePersistsEngineFields(t *testing.T) {
	dsn := fmt.Sprintf("file:fmreport_update_%d?mode=memory&cache=shared", time.Now().UnixNano())
	db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{NowFunc: func() time.Time { return time.Now().UTC() }})
	if err != nil {
		t.Fatalf("open: %v", err)
	}
	if err := db.AutoMigrate(&fmreport.Report{}); err != nil {
		t.Fatalf("migrate: %v", err)
	}
	repo := NewFMReportRepository(db)
	ctx := context.Background()

	flightID := uuidv7.MustBytes()
	// Seed an in-progress report with no engine values (like the user's).
	if err := repo.Upsert(ctx, &fmreport.Report{
		FlightID:           flightID,
		TakeoverID:         uuidv7.MustBytes(),
		FlightInspectionID: uuidv7.MustBytes(),
	}); err != nil {
		t.Fatalf("seed: %v", err)
	}

	// Apply the user's exact payload values.
	row, err := repo.GetByFlightID(ctx, flightID)
	if err != nil || row == nil {
		t.Fatalf("get seeded: %v row=%v", err, row)
	}
	e1g, e1p := "GPC/N1 63.2", "PTC/N2 61.8"
	e2g, e2p := "GPC/N1 63.2", "PTC/N2 61.8"
	row.Engine1GpcN1, row.Engine1PtcN2 = &e1g, &e1p
	row.Engine2GpcN1, row.Engine2PtcN2 = &e2g, &e2p
	if err := repo.Upsert(ctx, row); err != nil {
		t.Fatalf("update upsert: %v", err)
	}

	got, err := repo.GetByFlightID(ctx, flightID)
	if err != nil || got == nil {
		t.Fatalf("get after update: %v row=%v", err, got)
	}
	if got.Engine1GpcN1 == nil || *got.Engine1GpcN1 != "GPC/N1 63.2" {
		t.Fatalf("engine1_gpc_n1 = %v, want 'GPC/N1 63.2' (not persisted)", got.Engine1GpcN1)
	}
	if got.Engine1PtcN2 == nil || *got.Engine1PtcN2 != "PTC/N2 61.8" {
		t.Fatalf("engine1_ptc_n2 = %v, want 'PTC/N2 61.8'", got.Engine1PtcN2)
	}
	if got.Engine2GpcN1 == nil || *got.Engine2GpcN1 != "GPC/N1 63.2" {
		t.Fatalf("engine2_gpc_n1 = %v, want 'GPC/N1 63.2'", got.Engine2GpcN1)
	}
	t.Logf("engine fields persisted: e1_gpc=%q e1_ptc=%q e2_gpc=%q", *got.Engine1GpcN1, *got.Engine1PtcN2, *got.Engine2GpcN1)
}
