package cprelation

import (
	"errors"
	"testing"
)

func TestNormalizeRelationsForcesCPMaxCountAndKeepsSiblingLimits(t *testing.T) {
	relations, err := normalizeRelations([]relationDTO{
		relationInput(relationTypeCP, 99),
		relationInput(relationTypeBrother, 7),
		relationInput(relationTypeSister, 8),
	})
	if err != nil {
		t.Fatalf("normalizeRelations() error = %v", err)
	}

	got := map[string]int32{}
	for _, relation := range relations {
		got[relation.RelationType] = relation.MaxCountPerUser
	}
	if got[relationTypeCP] != 1 {
		t.Fatalf("CP max count = %d, want 1", got[relationTypeCP])
	}
	if got[relationTypeBrother] != 7 {
		t.Fatalf("brother max count = %d, want 7", got[relationTypeBrother])
	}
	if got[relationTypeSister] != 8 {
		t.Fatalf("sister max count = %d, want 8", got[relationTypeSister])
	}
}

func TestNormalizeRelationsRequiresIncreasingLevelThresholds(t *testing.T) {
	input := relationInput(relationTypeBrother, 5)
	input.Levels[2].IntimacyThreshold = input.Levels[1].IntimacyThreshold

	_, err := normalizeRelations([]relationDTO{
		relationInput(relationTypeCP, 1),
		input,
		relationInput(relationTypeSister, 5),
	})
	if !errors.Is(err, ErrInvalidArgument) {
		t.Fatalf("normalizeRelations() error = %v, want ErrInvalidArgument", err)
	}
}

func relationInput(relationType string, maxCount int32) relationDTO {
	return relationDTO{
		RelationType:           relationType,
		MaxCountPerUser:        maxCount,
		ApplicationExpireHours: defaultExpireHours,
		Status:                 statusActive,
		Levels: []levelDTO{
			{Level: 1, IntimacyThreshold: 0, Status: statusActive},
			{Level: 2, IntimacyThreshold: 10_000, Status: statusActive},
			{Level: 3, IntimacyThreshold: 30_000, Status: statusActive},
			{Level: 4, IntimacyThreshold: 60_000, Status: statusActive},
			{Level: 5, IntimacyThreshold: 100_000, Status: statusActive},
		},
	}
}
