using FastBlog.Core.Abstractions.Repositories.Files;
using FastBlog.Core.Models;
using FastBlog.Core.Options;
using Microsoft.Extensions.Options;

namespace FastBlog.Core.Repositories;

public sealed class FileRepository(IOptionsMonitor<FileStoreOptions> fileOptions) : IFileRepository
{
    public async Task<Result<bool, BusinessError>> Write(string path, Stream fileStream)
    {
        var targetPath = Path.Combine(fileOptions.CurrentValue.StaticFilesPath, path);
        var directoryPath = Path.GetDirectoryName(targetPath);

        if (!Directory.Exists(directoryPath))
            Directory.CreateDirectory(directoryPath!);

        if (File.Exists(targetPath))
            return new BusinessError("already_exists", "File already exists");

        await using var file = File.Create(targetPath);
        await fileStream.CopyToAsync(file);
        return true;

    }
    public Task<bool> Delete(string path)
    {
        var targetPath = Path.Combine(fileOptions.CurrentValue.StaticFilesPath, path);
        if (!File.Exists(targetPath))
            return Task.FromResult(false);
        File.Delete(targetPath);
        return Task.FromResult(true);
    }

}