namespace Ikar.Server.Infrastructure.Storage;

public sealed record AvatarStorageResult(string PhysicalPath, string ContentType);

public sealed class AvatarStorageService(IWebHostEnvironment environment)
{
    private readonly string _rootPath = Path.Combine(environment.ContentRootPath, "Data", "Avatars");

    public async Task<AvatarStorageResult> SaveAsync(Guid userId, IFormFile file, CancellationToken cancellationToken)
    {
        if (file.Length <= 0)
        {
            throw new InvalidOperationException("Avatar file is empty.");
        }

        Directory.CreateDirectory(_rootPath);

        var extension = Path.GetExtension(file.FileName);
        var safeExtension = string.IsNullOrWhiteSpace(extension) ? ".bin" : extension;
        var targetDirectory = Path.Combine(_rootPath, userId.ToString("N"));
        Directory.CreateDirectory(targetDirectory);

        var storedFileName = $"{Guid.NewGuid():N}{safeExtension}";
        var physicalPath = Path.Combine(targetDirectory, storedFileName);

        await using (var source = file.OpenReadStream())
        await using (var target = File.Create(physicalPath))
        {
            await source.CopyToAsync(target, cancellationToken);
        }

        var contentType = ResolveContentType(file.ContentType, safeExtension);

        return new AvatarStorageResult(physicalPath, contentType);
    }

    public void DeleteIfExists(string? physicalPath)
    {
        if (!string.IsNullOrWhiteSpace(physicalPath) && File.Exists(physicalPath))
        {
            File.Delete(physicalPath);
        }
    }

    private static string ResolveContentType(string? uploadedContentType, string extension) =>
        string.IsNullOrWhiteSpace(uploadedContentType)
            ? extension.ToLowerInvariant() switch
            {
                ".gif" => "image/gif",
                ".heic" => "image/heic",
                ".heif" => "image/heif",
                ".jpeg" => "image/jpeg",
                ".jpg" => "image/jpeg",
                ".png" => "image/png",
                ".webp" => "image/webp",
                _ => "application/octet-stream"
            }
            : uploadedContentType;
}
