package models

import "strings"

func qqNumericLocalPart(email string) string {
	e := strings.TrimSpace(strings.ToLower(email))
	if e == "" {
		return ""
	}
	at := strings.LastIndex(e, "@")
	if at <= 0 || at >= len(e)-1 {
		return ""
	}
	local, domain := e[:at], e[at+1:]
	if domain != "qq.com" {
		return ""
	}
	if local == "" {
		return ""
	}
	for _, r := range local {
		if r < '0' || r > '9' {
			return ""
		}
	}
	return local
}

func firstQQUINFromRecord(u UserRecord) string {
	if q := qqNumericLocalPart(u.Email); q != "" {
		return q
	}
	for _, em := range u.SecondaryEmails {
		if q := qqNumericLocalPart(em); q != "" {
			return q
		}
	}
	return ""
}

func qqAvatarHeadimgURL(uin string) string {
	return "https://q.qlogo.cn/headimg_dl?dst_uin=" + uin + "&spec=640&img_type=jpg"
}

// ResolvedAvatarURL 返回用户自选头像；若未设置但主邮箱或辅助邮箱为「纯数字 @qq.com」，
// 则返回 QQ 头像 CDN 地址（与手动填写该链接等价，不入库）。
func (u UserRecord) ResolvedAvatarURL() string {
	if s := strings.TrimSpace(u.AvatarURL); s != "" {
		return s
	}
	if uin := firstQQUINFromRecord(u); uin != "" {
		return qqAvatarHeadimgURL(uin)
	}
	return ""
}
