import APIClient
import ComposableArchitecture
import Foundation

@DependencyClient
public struct ClipDataClient {
    public var audioURL: (Clip) -> URL?
    public var save: @Sendable (Clip, Data) throws -> URL
}

extension ClipDataClient: DependencyKey {
    public static let liveValue: Self = {
        @Sendable func audioURL(of clip: Clip) -> URL {
            .temporaryDirectory
                .appending(component: "Downloads", directoryHint: .isDirectory)
                .appending(component: clip.id.remoteId, directoryHint: .isDirectory)
                .appending(component: "\(clip.title.lowercased().replacingOccurrences(of: " ", with: "-")).mp3")
        }

        return Self(
            audioURL: { clip in
                let url = audioURL(of: clip)
                return FileManager.default.fileExists(atPath: url.path) ? url : nil
            },
            save: { clip, data in
                let url = audioURL(of: clip)
                let fileManager = FileManager.default
                if !fileManager.fileExists(atPath: url.path) {
                    try fileManager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
                }
                try data.write(to: url)
                return url
            }
        )
    }()
}
