import Foundation

protocol BooksServiceProtocol {
    func searchByTitle(_ title: String, locales: String) async throws -> [BookRemote]
    func searchByISBN(_ isbn: String, locales: String) async throws -> [BookRemote]
    func filter(title: String, year: String, locales: String) async throws -> [BookRemote]
}

final class BooksService: BooksServiceProtocol {
    private let client: APIClientProtocol

    init(client: APIClientProtocol) {
        self.client = client
    }

    func searchByTitle(_ title: String, locales: String = "tr,en") async throws -> [BookRemote] {
        let response: BookSearchResponse = try await client.get(
            path: "api/books/title",
            queryItems: [
                .init(name: "title", value: title),
                .init(name: "locales", value: locales)
            ],
            token: nil
        )
        return response.items
    }

    func searchByISBN(_ isbn: String, locales: String = "tr,en") async throws -> [BookRemote] {
        let response: BookSearchResponse = try await client.get(
            path: "api/books/isbn/\(isbn)",
            queryItems: [
                .init(name: "locales", value: locales),
                .init(name: "withGemini", value: "false")
            ],
            token: nil
        )
        return response.items
    }

    func filter(title: String, year: String, locales: String = "tr,en") async throws -> [BookRemote] {
        let response: BookSearchResponse = try await client.get(
            path: "api/books/filter",
            queryItems: [
                .init(name: "title", value: title),
                .init(name: "published", value: year),
                .init(name: "locales", value: locales)
            ],
            token: nil
        )
        return response.items
    }
}
