package easarelease

import (
	"reflect"
	"testing"
	"time"
)

func str(s string) *string { return &s }

func TestEASAReleaseIsSigned(t *testing.T) {
	now := time.Now()
	if (&EASARelease{}).IsSigned() {
		t.Fatal("unsigned release reported as signed")
	}
	if !(&EASARelease{SignedAt: &now}).IsSigned() {
		t.Fatal("signed release reported as unsigned")
	}
	var nilRel *EASARelease
	if nilRel.IsSigned() {
		t.Fatal("nil release reported as signed")
	}
}

func TestEASAReleaseMissingSignFields(t *testing.T) {
	// Only the auto-filled signer is required to sign; the adjustable document
	// fields (date, A/C hours, location, WO no, manual revisions) are optional.
	onlySigner := []string{"easa_signer_id"}
	now := time.Now()

	cases := []struct {
		name string
		row  *EASARelease
		want []string
	}{
		{name: "nil requires signer", row: nil, want: onlySigner},
		{name: "empty requires signer", row: &EASARelease{}, want: onlySigner},
		{name: "signer present lists none", row: &EASARelease{EASASignerID: str("019d61db-53c6-7280-87ec-e65f205c6d3b")}, want: nil},
		{name: "other fields empty but signer set lists none", row: &EASARelease{EASASignerID: str("019d61db-53c6-7280-87ec-e65f205c6d3b"), EASADate: &now}, want: nil},
		{name: "blank signer counts as missing", row: &EASARelease{EASASignerID: str("")}, want: onlySigner},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			got := tc.row.MissingSignFields()
			if len(got) == 0 && len(tc.want) == 0 {
				return
			}
			if !reflect.DeepEqual(got, tc.want) {
				t.Fatalf("MissingSignFields() = %v, want %v", got, tc.want)
			}
		})
	}
}

func TestEASAReleaseIsActiveAndTableName(t *testing.T) {
	if (EASARelease{}).TableName() != "easa_releases" {
		t.Fatalf("unexpected table name")
	}
	now := time.Now()
	if (&EASARelease{}).IsActive() {
		t.Fatal("unsigned release must not be active")
	}
	if !(&EASARelease{SignedAt: &now}).IsActive() {
		t.Fatal("signed release must be active")
	}
}

func TestEASAReleaseBeforeCreate(t *testing.T) {
	e := &EASARelease{}
	if err := e.BeforeCreate(nil); err != nil {
		t.Fatalf("BeforeCreate err: %v", err)
	}
	if len(e.ID) == 0 {
		t.Fatal("BeforeCreate should set ID")
	}
	prev := string(e.ID)
	if err := e.BeforeCreate(nil); err != nil {
		t.Fatalf("BeforeCreate err: %v", err)
	}
	if string(e.ID) != prev {
		t.Fatal("BeforeCreate must not overwrite an existing ID")
	}
}
