package service

import (
	"context"

	roomv1 "hyapp.local/api/proto/room/v1"
	"hyapp/pkg/xerr"
)

// AdminRenameOwnerCountryCode 批量刷新房主国家码当前投影；它不是房间命令，不写 command log。
func (s *Service) AdminRenameOwnerCountryCode(ctx context.Context, req *roomv1.AdminRenameOwnerCountryCodeRequest) (*roomv1.AdminRenameOwnerCountryCodeResponse, error) {
	if s == nil || s.repository == nil {
		return nil, xerr.New(xerr.Unavailable, "room repository is not configured")
	}
	if req == nil {
		return nil, xerr.New(xerr.InvalidArgument, "country code rename request is required")
	}
	oldCountryCode := normalizeRoomCountryCode(req.GetOldCountryCode())
	newCountryCode := normalizeRoomCountryCode(req.GetNewCountryCode())
	if oldCountryCode == "" || newCountryCode == "" || oldCountryCode == newCountryCode {
		return nil, xerr.New(xerr.InvalidArgument, "country code rename is invalid")
	}

	nowMS := s.clock.Now().UTC().UnixMilli()
	result, err := s.repository.RenameOwnerCountryCode(ctx, oldCountryCode, newCountryCode, nowMS)
	if err != nil {
		return nil, err
	}
	if s.roomListCache != nil {
		// Redis 只承载发现页展示顺序，但国家 tab 会优先命中它；改码任务必须同步刷新缓存，避免成功后客户端短暂读到旧码。
		if err := s.RefreshRoomListCache(ctx); err != nil {
			return nil, err
		}
	}
	return &roomv1.AdminRenameOwnerCountryCodeResponse{
		RoomListEntries: result.RoomListEntries,
		RoomSnapshots:   result.RoomSnapshots,
		ServerTimeMs:    nowMS,
	}, nil
}
