//
//  ChatRoleViewModel.swift
//  Visual_Novel_iOS
//
//  Created by mh on 2025/11/6.
//

import Foundation
import CodableWrappers

// 角色列表相关

// request
struct RoleListRequest: Codable {
    var index = 1
    var limit = 20
    var name: String = ""
    var sourceId: String = ""
    var tagId: [String]?
}

// model
struct RoleListModel: Codable {
    var total: Int = 0
    var index: Int = -1
    var limit: Int = 0
    var rows: [RoleItem] = []
}

struct RoleItem: Codable {
    var id: String = ""
    var name: String = ""
    var coverImage: String = ""
    var score: Double?
    var description: String = ""
    var updateTime: String = ""
    var sourceId: String = ""
    var sourceType: Int = 0
    var commonCount: Int?
}

class ChatRoleViewModel {
    
    func loadRoles(index: Int, limit: Int = 10, name: String = "", sourceId: String = "", tagId: [String]? = nil, completion: ((_ datas: RoleListModel?) -> Void)?) {
        var req = RoleListRequest()
        req.index = index
        req.limit = limit
        req.name = name
        req.sourceId = sourceId
        req.tagId = tagId
        
        let params = req.toNonNilDictionary()
        
        // 根据 API 响应格式，返回的是单个 RoleListModel 对象，而不是数组
        // 但为了保持接口一致性，我们将单个对象包装成数组
        RoleProvider.request(.characterList(params: params), modelType: RoleListModel.self) { result in
            switch result {
            case .success(let model):
                // 如果返回的是单个 RoleListModel，将其包装成数组
                if let model = model {
                    completion?(model)
                } else {
                    completion?(nil)
                }
            case .failure(let failure):
                dlog("⛔️ 加载角色列表失败: \(failure)")
                completion?(nil)
            }
        }
    }
}
