using LiteCqrs;
using Microsoft.EntityFrameworkCore;
using TeleWave.Application.Common.Interfaces;
using TeleWave.Application.Common.Models;
using TeleWave.Domain.Library;

namespace TeleWave.Application.Library.Interstitials.ImportInterstitials;

public sealed class ImportInterstitialsCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<ImportInterstitialsCommand, Result<int>>
{
    public async Task<Result<int>> Handle(
        ImportInterstitialsCommand command,
        CancellationToken cancellationToken
    )
    {
        var ids = command.MediaAssetIds.Distinct().ToList();

        var assets = await dbContext
            .MediaAssets.AsNoTracking()
            .Where(a => ids.Contains(a.Id))
            .Select(a => new { a.Id, a.OriginalFileName })
            .ToListAsync(cancellationToken);
        if (assets.Count == 0)
            return Result.Failure<int>(ShowErrors.AssetNotFound);

        var alreadyUsed = await dbContext
            .Shows.SelectMany(s => s.Episodes)
            .Where(e => ids.Contains(e.MediaAssetId))
            .Select(e => e.MediaAssetId)
            .ToListAsync(cancellationToken);
        var used = alreadyUsed.ToHashSet();

        var created = 0;
        foreach (var asset in assets.Where(a => !used.Contains(a.Id)))
        {
            var show = Show.Create(ClipName(asset.OriginalFileName), ShowKind.Interstitial);
            show.AddEpisode(asset.Id);
            dbContext.Shows.Add(show);
            created++;
        }

        return Result.Success(created);
    }

    /// <summary>Имя ролика — имя файла без расширения; пустое (файл вида «.mp4») заменяем самим файлом.</summary>
    private static string ClipName(string fileName)
    {
        var name = Path.GetFileNameWithoutExtension(fileName);
        return string.IsNullOrWhiteSpace(name) ? fileName : name;
    }
}
