using TeleWave.Application.Common.Interfaces;

namespace TeleWave.Infrastructure.Media;

/// <summary>Файловое хранилище общего реестра изображений: images/{imageId}{ext}.</summary>
public sealed class ImageStore(MediaPathResolver paths) : IImageStore
{
    public async Task SaveAsync(
        Guid imageId,
        string extension,
        Stream content,
        CancellationToken cancellationToken
    )
    {
        Directory.CreateDirectory(paths.ImagesDir);
        var path = paths.ImagePath(imageId, Normalize(extension));
        await using var fs = File.Create(path);
        await content.CopyToAsync(fs, cancellationToken);
    }

    public async Task SaveAsync(
        Guid imageId,
        string extension,
        byte[] content,
        CancellationToken cancellationToken
    )
    {
        Directory.CreateDirectory(paths.ImagesDir);
        var path = paths.ImagePath(imageId, Normalize(extension));
        await File.WriteAllBytesAsync(path, content, cancellationToken);
    }

    public Task DeleteAsync(Guid imageId, string extension, CancellationToken cancellationToken)
    {
        var path = paths.ImagePath(imageId, Normalize(extension));
        if (File.Exists(path))
            File.Delete(path);
        return Task.CompletedTask;
    }

    public string? ResolvePath(Guid imageId, string extension)
    {
        var path = paths.ImagePath(imageId, Normalize(extension));
        return File.Exists(path) ? path : null;
    }

    private static string Normalize(string extension) =>
        extension.StartsWith('.') ? extension : "." + extension;
}
