/*
 * 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.remote

import org.dueattendant149.bookshelf.data.remote.bookshelfapi.BookshelfApiClientFactory
import org.dueattendant149.bookshelf.domain.util.isValidUri
import org.dueattendant149.bookshelf.domain.util.normalizeUri
import javax.inject.Inject

class CheckHealthUseCase
    @Inject
    constructor(
        private val clientFactory: BookshelfApiClientFactory,
    ) {
        suspend operator fun invoke(url: String): Result<Unit> {
            val trimmed = url.trim()
            if (trimmed.isBlank()) {
                return Result.failure(IllegalArgumentException("Bookshelf URL is empty"))
            }
            if (!trimmed.isValidUri()) {
                return Result.failure(IllegalArgumentException("Bookshelf URL is invalid: $trimmed"))
            }

            val normalized = trimmed.normalizeUri()
            val client = clientFactory.provideClient(normalized)
                ?: return Result.failure(IllegalStateException("Could not create API client for $normalized"))

            return runCatching {
                val response = client.health()
                if (!response.isSuccessful) {
                    throw IllegalStateException("Server returned HTTP ${response.code()}")
                }
            }
        }
    }
