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

namespace TeleWave.Application.Metadata.ApplyShowMetadata;

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

        var applied = await applier.ApplyAsync(
            show,
            command.Provider,
            command.ExternalId,
            cancellationToken
        );

        return applied.IsSuccess ? Result.Success() : Result.Failure(applied.Error);
    }
}
