package system

import (
	"context"
	"testing"
	"time"

	"kra/internal/biz"
)

func TestParameterRepositoryPreservesModelMetadata(t *testing.T) {
	data := newTransactionTestData(t)
	repo := &parameterRepo{data: data}
	createdAt := time.Date(2025, time.January, 2, 3, 4, 5, 0, time.Local)
	value := &biz.SystemParameter{ID: 41, CreatedAt: createdAt, Name: "name", Key: "key", Value: "value"}

	if err := repo.CreateParameter(context.Background(), value); err != nil {
		t.Fatal(err)
	}
	if value.ID != 41 || !value.CreatedAt.Equal(createdAt) {
		t.Fatalf("created parameter metadata = ID %d, CreatedAt %v", value.ID, value.CreatedAt)
	}

	nextCreatedAt := createdAt.Add(time.Hour)
	value.CreatedAt = nextCreatedAt
	value.Name = "updated"
	if err := repo.UpdateParameter(context.Background(), value); err != nil {
		t.Fatal(err)
	}
	var persisted parameterPO
	if err := data.gormDB.WithContext(context.Background()).First(&persisted, 41).Error; err != nil {
		t.Fatal(err)
	}
	if persisted.Name != "updated" || !persisted.CreatedAt.Equal(nextCreatedAt) {
		t.Fatalf("updated parameter = %+v", persisted)
	}
}

func TestParameterRepositoryKeepsReferenceEmptyQuerySemantics(t *testing.T) {
	data := newTransactionTestData(t)
	repo := &parameterRepo{data: data}
	ctx := context.Background()
	first := &biz.SystemParameter{Name: "first", Key: "first", Value: "1"}
	if err := repo.CreateParameter(ctx, first); err != nil {
		t.Fatal(err)
	}

	byEmptyKey, err := repo.FindParameterByKey(ctx, "")
	if err != nil {
		t.Fatal(err)
	}
	if byEmptyKey.ID != first.ID {
		t.Fatalf("empty key returned ID %d, want first row %d", byEmptyKey.ID, first.ID)
	}
	if _, err = repo.FindParameterByID(ctx, ""); err == nil {
		t.Fatal("empty ID unexpectedly matched a parameter")
	}
	if err = repo.DeleteParameters(ctx, nil); err != nil {
		t.Fatalf("empty bulk delete must be a successful no-op: %v", err)
	}
	var count int64
	if err = data.gormDB.WithContext(ctx).Model(&parameterPO{}).Count(&count).Error; err != nil {
		t.Fatal(err)
	}
	if count != 1 {
		t.Fatalf("empty bulk delete removed rows: count=%d", count)
	}
}
