package grpc

import (
	"reflect"
	"testing"

	hostdomain "hyapp/services/user-service/internal/domain/host"
	userdomain "hyapp/services/user-service/internal/domain/user"
	userservice "hyapp/services/user-service/internal/service/user"
)

func TestToProtoUserAdminProfilePreservesOwnerFacts(t *testing.T) {
	profile := userdomain.AdminProfile{
		User:                 userdomain.User{UserID: 10001, Status: userdomain.StatusBanned},
		BirthDate:            "2000-02-03",
		RegisterDevice:       "Pixel 9",
		LastSuccessLoginAtMs: 4_000,
		Roles:                []string{userdomain.AdminRoleHost, userdomain.AdminRoleManager},
		Ban: userdomain.ActiveBanSummary{
			Active: true, Source: userdomain.BanSourceAdmin, BanID: "admin-ban-1",
			Permanent: true, UserStatus: userdomain.StatusBanned, OperatorType: "admin",
			OperatorUserID: 9001, ActiveBanCount: 2,
		},
		LastOperatorType:    "admin",
		LastOperatorUserID:  9001,
		LastOperationReason: "admin_user_ban:admin-ban-1",
		LastOperationAtMs:   4_000,
	}

	got := toProtoUserAdminProfile(profile)
	if got.GetUser().GetUserId() != 10001 || got.GetBirth() != profile.BirthDate || got.GetRegisterDevice() != profile.RegisterDevice {
		t.Fatalf("admin profile base projection mismatch: %+v", got)
	}
	if !reflect.DeepEqual(got.GetRoles(), profile.Roles) || !got.GetBan().GetPermanent() || got.GetBan().GetActiveBanCount() != 2 {
		t.Fatalf("admin profile role/ban projection mismatch: %+v", got)
	}
}

func TestToProtoAdminUserBanMarksZeroExpiryPermanent(t *testing.T) {
	got := toProtoAdminUserBan(userservice.AdminUserBan{
		BanID: "admin-ban-1", TargetUserID: 10001, ExpiresAtMs: 0, Status: userservice.AdminUserBanStatusActive,
	})
	if got == nil || !got.GetPermanent() || got.GetExpiresAtMs() != 0 {
		t.Fatalf("zero expiry must be exposed as permanent: %+v", got)
	}
}

func TestRoleNamesFromSummaryKeepsStableMultiRoleOrder(t *testing.T) {
	roles := roleNamesFromSummary(hostdomain.UserRoleSummary{
		IsHost: true, IsAgency: true, IsBD: true, IsBDLeader: true, IsCoinSeller: true, IsManager: true,
	})
	want := []string{
		userdomain.AdminRoleHost,
		userdomain.AdminRoleAgency,
		userdomain.AdminRoleBD,
		userdomain.AdminRoleBDLeader,
		userdomain.AdminRoleCoinSeller,
		userdomain.AdminRoleManager,
	}
	if !reflect.DeepEqual(roles, want) {
		t.Fatalf("role order mismatch: got=%v want=%v", roles, want)
	}
}
