using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Domain.Media;

namespace TeleWave.Application.Storage;

public sealed class GetStorageStatsQueryHandler(
    IAppDbContext dbContext,
    IStorageInspector inspector
) : IQueryHandler<GetStorageStatsQuery, StorageStatsDto>
{
    public async Task<StorageStatsDto> Handle(
        GetStorageStatsQuery query,
        CancellationToken cancellationToken
    )
    {
        // Сегменты программ и заставок лежат в одном каталоге; отличить их можно только по базе.
        var generated = await dbContext
            .MediaAssets.AsNoTracking()
            .Where(a => a.Source == MediaSource.Generated)
            .Select(a => a.Id)
            .ToListAsync(cancellationToken);

        var usage = await inspector.InspectAsync(
            generated.ToHashSet(),
            query.Refresh,
            cancellationToken
        );

        return new StorageStatsDto(
            usage.RootPath,
            usage.VolumeTotalBytes,
            usage.VolumeFreeBytes,
            usage.StorageBytes,
            usage.StorageFiles,
            usage.MinFreeSpaceBytes,
            usage.Areas.Select(a => new StorageAreaDto(a.Area, a.Bytes, a.Files)).ToList(),
            usage.ComputedAt
        );
    }
}
