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

import Foundation
import Combine

/// 消息中心服务协议，定义消息列表、已读和删除能力。
@MainActor
protocol MessageCenterServing {
    /// 获取消息列表，使用 last_id 游标分页。
    func messageList(lastId: Int, limit: Int, unread: Int) async throws -> MessageListResponse

    /// 标记单条消息为已读。
    func messageRead(id: Int) async throws

    /// 删除单条消息。
    func messageDelete(id: Int) async throws
}

@MainActor
/// 消息中心 API，封装消息相关网络请求。
final class MessageCenterAPI {
    private let client: APIClient

    /// 初始化消息中心 API，并注入共享网络客户端。
    init(client: APIClient) {
        self.client = client
    }

    /// 获取消息列表，使用 last_id 游标分页。
    func messageList(lastId: Int = 0, limit: Int = 20, unread: Int = 0) async throws -> MessageListResponse {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/app/msg/list",
                queryItems: [
                    URLQueryItem(name: "last_id", value: String(max(lastId, 0))),
                    URLQueryItem(name: "limit", value: String(max(limit, 1))),
                    URLQueryItem(name: "unread", value: String(max(unread, 0)))
                ]
            )
        )
    }

    /// 标记单条消息为已读。
    func messageRead(id: Int) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/app/msg/read",
                queryItems: [URLQueryItem(name: "id", value: String(id))],
                body: EmptyPayload()
            )
        )
    }

    /// 删除单条消息。
    func messageDelete(id: Int) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/app/msg/delete",
                body: MessageDeleteRequest(id: id)
            )
        )
    }
}

extension MessageCenterAPI: MessageCenterServing {}
