package user

import (
	"context"
	"testing"

	"hyapp/pkg/appcode"
	"hyapp/pkg/xerr"
	userdomain "hyapp/services/user-service/internal/domain/user"
)

func TestSearchInviteReferrerAllowsDifferentCountryInSameRegion(t *testing.T) {
	repository := &fakeModerationRepository{
		user: userdomain.User{
			AppCode:          "lalu",
			UserID:           330307556184428544,
			Country:          "SG",
			RegionID:         3,
			ProfileCompleted: true,
			Status:           userdomain.StatusActive,
		},
		inviteReferrer: userdomain.User{
			AppCode:          "lalu",
			UserID:           312900014781243392,
			Country:          "AT",
			RegionID:         3,
			ProfileCompleted: true,
			Status:           userdomain.StatusActive,
		},
	}
	svc := New(repository)

	found, err := svc.SearchInviteReferrer(appcode.WithContext(context.Background(), "lalu"), 330307556184428544, " a5uzc4mt ")
	if err != nil {
		t.Fatalf("same-region invite referrer search failed: %v", err)
	}
	if found.UserID != 312900014781243392 {
		t.Fatalf("same-region invite referrer mismatch: %+v", found)
	}
	if repository.lastFindAppCode != "lalu" || repository.lastFindInviteCode != "A5UZC4MT" {
		t.Fatalf("invite code lookup should use normalized app/code: app=%q code=%q", repository.lastFindAppCode, repository.lastFindInviteCode)
	}
}

func TestSearchInviteReferrerRejectsDifferentRegion(t *testing.T) {
	repository := &fakeModerationRepository{
		user: userdomain.User{
			AppCode:          "lalu",
			UserID:           10001,
			Country:          "SG",
			RegionID:         3,
			ProfileCompleted: true,
			Status:           userdomain.StatusActive,
		},
		inviteReferrer: userdomain.User{
			AppCode:          "lalu",
			UserID:           10002,
			Country:          "US",
			RegionID:         4,
			ProfileCompleted: true,
			Status:           userdomain.StatusActive,
		},
	}
	svc := New(repository)

	_, err := svc.SearchInviteReferrer(appcode.WithContext(context.Background(), "lalu"), 10001, "A5UZC4MT")
	if xerr.CodeOf(err) != xerr.NotFound {
		t.Fatalf("different-region invite referrer must be hidden as not found, err=%v", err)
	}
}
