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

import Foundation

/// 旅拍相册素材上传器，实现 OSS 上传 + 后端 upload-material 登记。
@MainActor
final class TravelAlbumMaterialUploader: CameraAssetUploadSink {
    private let api: any TravelAlbumServing
    private let ossService: any OSSUploadServing
    private let albumID: Int
    private let scenicID: Int

    /// 初始化上传器，注入 API、OSS 与业务上下文。
    init(api: any TravelAlbumServing, ossService: any OSSUploadServing, albumID: Int, scenicID: Int) {
        self.api = api
        self.ossService = ossService
        self.albumID = albumID
        self.scenicID = scenicID
    }

    /// 上传本地文件到 OSS 并登记到旅拍相册。
    func upload(
        localURL: URL,
        fileName: String,
        fileType: Int,
        progress: @escaping @Sendable (Int) -> Void
    ) async throws -> String {
        guard albumID > 0 else {
            throw APIError.serverCode(0, "请先选择有效的相册")
        }
        guard FileManager.default.fileExists(atPath: localURL.path) else {
            throw APIError.serverCode(0, "相机文件读取失败")
        }

        let data = try Data(contentsOf: localURL)
        guard !data.isEmpty else {
            throw APIError.serverCode(0, "相机文件读取失败")
        }

        let remoteURL = try await ossService.uploadAlbumFile(
            data: data,
            fileName: fileName,
            fileType: fileType,
            scenicId: scenicID,
            onProgress: progress
        )

        _ = try await api.uploadMaterial(
            TravelAlbumUploadMaterialRequest(
                userEquityTravelId: albumID,
                fileName: fileName,
                fileURL: remoteURL
            )
        )

        return remoteURL
    }
}
