/*
 * 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.core.log.logW
import org.dueattendant149.bookshelf.domain.model.library.Book
import org.dueattendant149.bookshelf.domain.repository.BookRepository
import org.dueattendant149.bookshelf.domain.repository.HistoryRepository
import org.dueattendant149.bookshelf.domain.service.CoverImageHandler
import javax.inject.Inject

private const val TAG = "DeleteBook"

class DeleteBookUseCase @Inject constructor(
    private val bookRepository: BookRepository,
    private val historyRepository: HistoryRepository,
    private val coverImageHandler: CoverImageHandler
) {

    suspend operator fun invoke(book: Book) {
        logI(TAG, "Deleting [${book.title}].")

        // Deleting cover image
        book.coverImage?.let { coverImageHandler.deleteCover(it) }?.onFailure {
            logW(TAG, "Could not delete cover image with error: ${it.message}")
        }

        // Deleting history
        historyRepository.deleteHistoryForBook(bookId = book.id).onFailure {
            logW(TAG, "Could not delete history for [${book.title}] with error: ${it.message}")
        }

        // Deleting book
        bookRepository.deleteBook(book).fold(
            onSuccess = {
                logI(TAG, "Successfully deleted [${book.title}].")
            },
            onFailure = {
                logE(TAG, "Could not delete [${book.title}] with error: ${it.message}")
            }
        )
    }
}