//
//  CooperationAcquirerViewModel.swift
//  suixinkan
//
//  Created by Codex on 2026/6/29.
//

import Foundation
import Combine

/// 合作获客员列表 ViewModel。
@MainActor
final class CooperationAcquirerViewModel: ObservableObject {
    @Published var acquirers: [CooperativeSaler] = []
    @Published private(set) var hasLoadedOnce = false

    /// 重新加载当前门店下的合作获客员。
    func reload(api: CooperationOrderServing, storeId: Int?) async {
        do {
            let storeParam = storeId.flatMap { $0 > 0 ? $0 : nil }
            let data = try await api.cooperativeSalers(storeId: storeParam, page: 1, pageSize: 20)
            acquirers = data.list
        } catch {
            if !hasLoadedOnce {
                acquirers = []
            }
        }
        hasLoadedOnce = true
    }

    /// 更新指定获客员的备注名，成功后刷新本地列表项。
    func updateRemark(
        saleUserId: Int,
        remark: String,
        api: CooperationOrderServing
    ) async throws {
        guard saleUserId > 0 else { return }
        if let message = CooperationOrderRemarkName.validationMessage(for: remark) {
            throw CooperationOrderRemarkValidationError(message: message)
        }
        let trimmedRemark = CooperationOrderRemarkName.trimmed(remark)
        try await api.saleUserUpdateRemark(saleUserId: saleUserId, photogRemarkName: trimmedRemark)
        acquirers = acquirers.map { acquirer in
            guard acquirer.saleUserId == saleUserId else { return acquirer }
            return acquirer.withPhotogRemarkName(trimmedRemark)
        }
    }
}

/// 合作获客员备注名校验失败错误。
struct CooperationOrderRemarkValidationError: LocalizedError {
    let message: String

    var errorDescription: String? { message }
}
