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

namespace TeleWave.Application.Library.AddEpisode;

public sealed class AddEpisodeCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<AddEpisodeCommand, Result<Guid>>
{
    public async Task<Result<Guid>> Handle(
        AddEpisodeCommand command,
        CancellationToken cancellationToken
    )
    {
        var show = await dbContext
            .Shows.Include(s => s.Episodes)
            .FirstOrDefaultAsync(s => s.Id == command.ShowId, cancellationToken);
        if (show is null)
            return Result.Failure<Guid>(ShowErrors.NotFound);

        if (!show.CanAddEpisode)
            return Result.Failure<Guid>(ShowErrors.SingleAlreadyHasEpisode);

        var fileName = await dbContext
            .MediaAssets.Where(a => a.Id == command.MediaAssetId)
            .Select(a => a.OriginalFileName)
            .FirstOrDefaultAsync(cancellationToken);
        if (fileName is null)
            return Result.Failure<Guid>(ShowErrors.AssetNotFound);

        var episode = show.AddEpisode(command.MediaAssetId);
        if (EpisodeName.Parse(fileName) is { } parsed)
            episode.SetNumbers(parsed.Season, parsed.Episode);

        return Result.Success(episode.Id);
    }
}
