/*
 * Book's Story — free and open-source Material You eBook reader.
 * Copyright (C) 2024-2026 Acclorite
 * SPDX-License-Identifier: GPL-3.0-only
 */

package org.dueattendant149.bookshelf.domain.use_case.book

import org.dueattendant149.bookshelf.core.log.logE
import org.dueattendant149.bookshelf.core.log.logI
import org.dueattendant149.bookshelf.domain.model.library.Book
import org.dueattendant149.bookshelf.domain.repository.BookRepository
import org.dueattendant149.bookshelf.domain.repository.HistoryRepository
import javax.inject.Inject

private const val TAG = "SearchBooks"

class SearchBooksUseCase @Inject constructor(
    private val bookRepository: BookRepository,
    private val historyRepository: HistoryRepository
) {

    suspend operator fun invoke(query: String): List<Book> {
        logI(TAG, "Searching for books with query: \"$query\".")

        return bookRepository.searchBooks(query).fold(
            onSuccess = { books ->
                logI(TAG, "Successfully found [${books.size}] books.")
                books.map { book ->
                    val history = historyRepository.getHistoryForBook(book.id).getOrNull()

                    book.copy(
                        lastOpened = history?.time
                    )
                }
            },
            onFailure = {
                logE(TAG, "Could not find books with error: ${it.message}")
                emptyList()
            }
        )
    }
}