//
//  AppFormValidator.swift
//  suixinkan
//
//  Created by Codex on 2026/6/25.
//

import Foundation

/// 表单校验工具，承接排队设置等页面的通用数字和金额格式校验。
enum AppFormValidator {
    /// 规范化大陆手机号，去除所有空白字符。
    static func normalizedPhoneNumber(_ value: String) -> String {
        value.filter { !$0.isWhitespace }
    }

    /// 校验大陆 11 位手机号基础号段。
    static func isValidMainlandPhoneNumber(_ value: String) -> Bool {
        let phone = normalizedPhoneNumber(value)
        guard phone.count == 11, phone.first == "1" else { return false }
        return phone.allSatisfy(\.isNumber)
    }

    /// 校验整数文本在指定范围内。
    static func rangedInteger(_ text: String, name: String, range: ClosedRange<Int>) throws -> Int {
        let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty, let value = Int(trimmed) else {
            throw APIError.networkFailed("\(name)格式不正确")
        }
        guard range.contains(value) else {
            throw APIError.networkFailed("\(name)须在 \(range.lowerBound)～\(range.upperBound)")
        }
        return value
    }

    /// 校验两次通知阈值，第二次应小于等于第一次。
    static func validateQueueNoticeThresholds(first: Int, second: Int) throws {
        guard second <= first else {
            throw APIError.networkFailed("第二次通知阈值不能大于第一次通知阈值")
        }
    }

    /// 清洗最多指定小数位的金额输入。
    static func sanitizedMoneyInput(_ input: String, maxDecimalPlaces: Int = 2) -> String {
        var result = ""
        var hasDot = false
        var decimalCount = 0

        for char in input {
            if char.isNumber {
                if hasDot {
                    guard decimalCount < maxDecimalPlaces else { continue }
                    decimalCount += 1
                }
                result.append(char)
            } else if char == ".", !hasDot {
                hasDot = true
                result.append(char)
            }
        }

        if result.hasPrefix(".") {
            result = "0" + result
        }
        return result
    }

    /// 规范化提交用金额，最多两位小数。
    static func normalizedMoneyForSubmit(_ input: String) -> String {
        let sanitized = sanitizedMoneyInput(input, maxDecimalPlaces: 2)
        guard !sanitized.isEmpty, sanitized != "." else { return "" }
        return sanitized
    }
}
