import Foundation
import Hummingbird

struct FileProviderMock {
    
    // MARK: Properties
    
    private var attributes: [String: Data] = [:]
    private var identifiers: [String] = []
    
    // MARK: Functions
    
    mutating func setFile(identifier: String) {
        identifiers += [identifier]
        attributes[identifier] = identifier.data(using: .utf8)
    }
    
}

// MARK: - FileProvider

extension FileProviderMock: FileProvider {
    
    // MARK: Type aliases

    typealias FileAttributes = Data
    typealias FileIdentifier = String
    
    // MARK: Functions

    func getFileIdentifier(_ path: String) -> String? {
        identifiers.first { $0 == path }
    }
    
    func getAttributes(id: String) async throws -> Data? {
        attributes[id]
    }
    
    func loadFile(id: String, context: some RequestContext) async throws -> ResponseBody {
        guard let fileData = attributes[id] else {
            throw HTTPError(.notFound)
        }

        return .init(byteBuffer: .init(data: fileData))
    }
    
    func loadFile(
        id: String,
        range: ClosedRange<Int>,
        context: some RequestContext
    ) async throws -> ResponseBody {
        try await loadFile(id: id, context: context)
    }
    
}
