using FluentResults;
using NexusReader.Application.Abstractions.Services;
using NexusReader.Application.Queries.Reader;
using VersOne.Epub;

namespace NexusReader.Infrastructure.Services;

/// <summary>
/// Extracts metadata (title, author, cover image) from an EPUB stream without persisting anything.
/// Used by the ingestion UI before the user confirms the upload.
/// </summary>
public class EpubMetadataExtractor : IEpubMetadataExtractor
{
    /// <inheritdoc />
    public async Task<Result<LocalEpubMetadata>> ExtractMetadataAsync(Stream epubStream)
    {
        try
        {
            using var bookRef = await EpubReader.OpenBookAsync(epubStream);
            var title = bookRef.Title ?? "Unknown Title";
            var author = bookRef.Author ?? "Unknown Author";
            var description = bookRef.Description;
            byte[]? cover = await bookRef.ReadCoverAsync();
            return Result.Ok(new LocalEpubMetadata { Title = title, Author = author, CoverImage = cover, Description = description });
        }
        catch (Exception ex)
        {
            return Result.Fail(new Error($"Failed to extract EPUB metadata locally: {ex.Message}").CausedBy(ex));
        }
    }
}
