//
//  LiveAPI.swift
//  suixinkan
//

import Foundation

/// 直播服务协议，抽象 manual-live 与 view-album 接口。
@MainActor
protocol LiveServing {
    /// 拉取直播列表。
    func liveList(scenicId: String, page: Int, pageSize: Int) async throws -> LiveListResponse

    /// 拉取直播详情。
    func liveDetail(liveId: Int) async throws -> LiveItem

    /// 新建直播。
    func createLive(scenicId: String, title: String, coverImg: String) async throws

    /// 开始直播。
    func startLive(liveId: Int) async throws

    /// 暂停直播。
    func stopLive(liveId: Int) async throws

    /// 结束直播。
    func finishLive(liveId: Int) async throws

    /// 设置直播推流模式。
    func setPushMode(liveId: Int, mode: Int) async throws

    /// 拉取直播相册列表。
    func albumList(scenicId: String, startTime: String?, endTime: String?, page: Int, pageSize: Int) async throws -> LiveAlbumFolderListResponse

    /// 创建直播相册文件夹。
    func createAlbumFolder(scenicId: String, name: String, items: [LiveAlbumFile]) async throws

    /// 删除直播相册文件夹。
    func deleteAlbumFolder(folderId: Int) async throws

    /// 拉取直播相册详情。
    func albumFolderDetail(folderId: Int) async throws -> LiveAlbumFolder

    /// 删除直播相册素材。
    func deleteAlbumFile(folderId: Int, fileId: Int) async throws
}

/// 直播 API，封装 Android `NetworkApi` 中 alive/manual-live 与 view-album 接口。
@MainActor
final class LiveAPI: LiveServing {
    private let client: APIClient

    /// 初始化直播 API。
    init(client: APIClient) {
        self.client = client
    }

    /// 拉取直播列表。
    func liveList(scenicId: String, page: Int = 1, pageSize: Int = 10) async throws -> LiveListResponse {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/app/manual-live/list",
                queryItems: [
                    URLQueryItem(name: "scenic_id", value: scenicId),
                    URLQueryItem(name: "page", value: String(max(page, 1))),
                    URLQueryItem(name: "page_size", value: String(max(pageSize, 1))),
                ]
            )
        )
    }

    /// 拉取直播详情。
    func liveDetail(liveId: Int) async throws -> LiveItem {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/app/manual-live/detail",
                queryItems: [URLQueryItem(name: "live_id", value: String(liveId))]
            )
        )
    }

    /// 新建直播。
    func createLive(scenicId: String, title: String, coverImg: String) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/app/manual-live/create",
                body: LiveCreateRequest(scenicId: scenicId, title: title, coverImg: coverImg)
            )
        )
    }

    /// 开始直播。
    func startLive(liveId: Int) async throws {
        try await controlLive(path: "/api/app/manual-live/start", liveId: liveId)
    }

    /// 暂停直播。
    func stopLive(liveId: Int) async throws {
        try await controlLive(path: "/api/app/manual-live/stop", liveId: liveId)
    }

    /// 结束直播。
    func finishLive(liveId: Int) async throws {
        try await controlLive(path: "/api/app/manual-live/finish", liveId: liveId)
    }

    /// 设置直播推流模式。
    func setPushMode(liveId: Int, mode: Int) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/app/manual-live/set-push-mode",
                body: LivePushModeRequest(liveId: liveId, manualPushMode: mode)
            )
        )
    }

    /// 拉取直播相册列表。
    func albumList(
        scenicId: String,
        startTime: String? = nil,
        endTime: String? = nil,
        page: Int = 1,
        pageSize: Int = 10
    ) async throws -> LiveAlbumFolderListResponse {
        var items = [
            URLQueryItem(name: "scenic_id", value: scenicId),
            URLQueryItem(name: "page", value: String(max(page, 1))),
            URLQueryItem(name: "page_size", value: String(max(pageSize, 1))),
        ]
        if let startTime, !startTime.isEmpty {
            items.append(URLQueryItem(name: "start_time", value: startTime))
        }
        if let endTime, !endTime.isEmpty {
            items.append(URLQueryItem(name: "end_time", value: endTime))
        }
        return try await client.send(
            APIRequest(method: .get, path: "/api/app/view-album/folders", queryItems: items)
        )
    }

    /// 创建直播相册文件夹。
    func createAlbumFolder(scenicId: String, name: String, items: [LiveAlbumFile]) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/app/view-album/create-folder",
                body: LiveAlbumFolderCreateRequest(scenicId: scenicId, name: name, items: items)
            )
        )
    }

    /// 删除直播相册文件夹。
    func deleteAlbumFolder(folderId: Int) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/app/view-album/delete-folder",
                body: LiveAlbumFolderDeleteRequest(folderId: folderId)
            )
        )
    }

    /// 拉取直播相册详情。
    func albumFolderDetail(folderId: Int) async throws -> LiveAlbumFolder {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/app/view-album/folder-detail",
                queryItems: [URLQueryItem(name: "folder_id", value: String(folderId))]
            )
        )
    }

    /// 删除直播相册素材。
    func deleteAlbumFile(folderId: Int, fileId: Int) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/app/view-album/delete-files",
                body: LiveAlbumFileDeleteRequest(folderId: folderId, fileIds: [fileId])
            )
        )
    }

    private func controlLive(path: String, liveId: Int) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(method: .post, path: path, body: LiveControlRequest(liveId: liveId))
        )
    }
}
