using FastBlog.Core.Abstractions.Repositories.Files;
using FastBlog.Core.Models;
using FastBlog.Core.Models.Files;

namespace FastBlog.Core.Services;

public sealed class FileService(IFileMetaRepository metaRepository, IFileRepository repository)
{
    public Task<PagedResponse<FileMeta>> GetFiles(PagedRequest request) => metaRepository.List(request);

    public async Task<bool> DeleteFile(int metaId)
    {
        var meta = await metaRepository.Get(metaId);
        
        if (meta is null)
            return false;

        var result =  await metaRepository.Delete(meta);
        if (!result)
            return result;
        
        return await repository.Delete(meta.SourceLocation);
    }

    public async Task<Result<FileMeta, BusinessError>> AddFile(FileMeta meta, Func<Stream> streamProvider)
    {
        var metaResult =  await metaRepository.Add(meta);

        if (metaResult.IsError)
            return metaResult.AsError;

        await using var stream = streamProvider();
        var result = await repository.Write(meta.SourceLocation, stream);

        return result.IsError ? metaResult.AsError : metaResult;
    }
}