package mcf

import (
	"testing"
	"time"
)

func result(v string) *string { return &v }

func TestMaintenanceCheckFlightState(t *testing.T) {
	now := time.Now()
	cases := []struct {
		name         string
		row          *MaintenanceCheckFlight
		wantComplete bool
		wantCleared  bool
		wantPending  bool
	}{
		{name: "nil", row: nil, wantComplete: false, wantCleared: false, wantPending: false},
		{name: "draft (not flown)", row: &MaintenanceCheckFlight{}, wantComplete: false, wantCleared: false, wantPending: true},
		// Once signed the MCF is done regardless of result — signing clears MCF status.
		{name: "signed failed is done", row: &MaintenanceCheckFlight{CompletedAt: &now, Result: result(ResultFailed)}, wantComplete: true, wantCleared: true, wantPending: false},
		{name: "signed passed is done", row: &MaintenanceCheckFlight{CompletedAt: &now, Result: result(ResultPassed)}, wantComplete: true, wantCleared: true, wantPending: false},
		{name: "result set without completedAt still pending", row: &MaintenanceCheckFlight{Result: result(ResultFailed)}, wantComplete: false, wantCleared: false, wantPending: true},
		// A draft edited with result=passed but NOT yet signed must NOT clear the aircraft.
		{name: "passed result on unsigned draft is NOT cleared", row: &MaintenanceCheckFlight{Result: result(ResultPassed)}, wantComplete: false, wantCleared: false, wantPending: true},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			if got := tc.row.IsComplete(); got != tc.wantComplete {
				t.Errorf("IsComplete() = %v, want %v", got, tc.wantComplete)
			}
			if got := tc.row.IsCleared(); got != tc.wantCleared {
				t.Errorf("IsCleared() = %v, want %v", got, tc.wantCleared)
			}
			if got := tc.row.IsPending(); got != tc.wantPending {
				t.Errorf("IsPending() = %v, want %v", got, tc.wantPending)
			}
		})
	}
}

func TestIsValidResult(t *testing.T) {
	cases := []struct {
		in   string
		want bool
	}{
		{ResultPassed, true},
		{ResultFailed, true},
		{"partial", false},
		{"", false},
		{"PASSED", false},
	}
	for _, tc := range cases {
		t.Run(tc.in, func(t *testing.T) {
			if got := IsValidResult(tc.in); got != tc.want {
				t.Fatalf("IsValidResult(%q) = %v, want %v", tc.in, got, tc.want)
			}
		})
	}
}

func TestMCFTableNameAndBeforeCreate(t *testing.T) {
	if (MaintenanceCheckFlight{}).TableName() != "maintenance_check_flights" {
		t.Fatalf("unexpected table name")
	}
	m := &MaintenanceCheckFlight{}
	if err := m.BeforeCreate(nil); err != nil {
		t.Fatalf("BeforeCreate err: %v", err)
	}
	if len(m.ID) == 0 {
		t.Fatal("BeforeCreate should set ID")
	}
	prev := string(m.ID)
	if err := m.BeforeCreate(nil); err != nil {
		t.Fatalf("BeforeCreate err: %v", err)
	}
	if string(m.ID) != prev {
		t.Fatal("BeforeCreate must not overwrite an existing ID")
	}
}
