//
//  CloudTransferJSONStore.swift
//  suixinkan
//

import Foundation

/// JSON 文件实现的云盘传输任务存储。
final class CloudTransferJSONStore: CloudTransferTaskStoring {
    private let fileURL: URL
    private let encoder = JSONEncoder()
    private let decoder = JSONDecoder()

    /// 初始化本地 JSON 存储。
    init(fileURL: URL? = nil) {
        if let fileURL {
            self.fileURL = fileURL
        } else {
            let baseURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
                ?? FileManager.default.temporaryDirectory
            self.fileURL = baseURL
                .appendingPathComponent("suixinkan", isDirectory: true)
                .appendingPathComponent("cloud_transfer_tasks.json")
        }
    }

    func loadTasks() -> [CloudTransferTask] {
        guard let data = try? Data(contentsOf: fileURL) else { return [] }
        return (try? decoder.decode([CloudTransferTask].self, from: data)) ?? []
    }

    func saveTasks(_ tasks: [CloudTransferTask]) {
        do {
            let directory = fileURL.deletingLastPathComponent()
            try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
            let data = try encoder.encode(tasks)
            try data.write(to: fileURL, options: [.atomic])
        } catch {
            #if DEBUG
            print("CloudTransferJSONStore save failed: \(error)")
            #endif
        }
    }
}
