package validator

import (
	"regexp"

	"github.com/break/junhong_cmp_fiber/pkg/constants"
)

var iccidRegex = regexp.MustCompile(`^[0-9A-Za-z]+$`)

type ICCIDValidationResult struct {
	Valid   bool
	Message string
}

// ValidateICCID 根据运营商类型验证 ICCID 格式
// carrierType: 运营商类型编码 (CMCC/CUCC/CTCC/CBN)
// 电信(CTCC) ICCID 长度为 19 位，其他运营商为 20 位
func ValidateICCID(iccid string, carrierType string) ICCIDValidationResult {
	if iccid == "" {
		return ICCIDValidationResult{Valid: false, Message: "ICCID 不能为空"}
	}

	if !iccidRegex.MatchString(iccid) {
		return ICCIDValidationResult{Valid: false, Message: "ICCID 只能包含字母和数字"}
	}

	length := len(iccid)
	expectedLength := getExpectedICCIDLength(carrierType)

	if length != expectedLength {
		if carrierType == constants.CarrierCodeCTCC {
			return ICCIDValidationResult{Valid: false, Message: "电信 ICCID 必须为 19 位"}
		}
		return ICCIDValidationResult{Valid: false, Message: "该运营商 ICCID 必须为 20 位"}
	}

	return ICCIDValidationResult{Valid: true, Message: ""}
}

func getExpectedICCIDLength(carrierType string) int {
	if carrierType == constants.CarrierCodeCTCC {
		return 19
	}
	return 20
}

func ValidateICCIDWithoutCarrier(iccid string) ICCIDValidationResult {
	if iccid == "" {
		return ICCIDValidationResult{Valid: false, Message: "ICCID 不能为空"}
	}

	if !iccidRegex.MatchString(iccid) {
		return ICCIDValidationResult{Valid: false, Message: "ICCID 只能包含字母和数字"}
	}

	length := len(iccid)
	if length != 19 && length != 20 {
		return ICCIDValidationResult{Valid: false, Message: "ICCID 长度必须为 19 位或 20 位"}
	}

	return ICCIDValidationResult{Valid: true, Message: ""}
}
