using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace ErsatzTV.Application.Playouts;

public class GetPlayoutItemSchedulingContextHandler(
    IDbContextFactory<TvContext> dbContextFactory,
    IMediator mediator)
    : IRequestHandler<GetPlayoutItemSchedulingContext, Option<string>>
{
    public async Task<Option<string>> Handle(
        GetPlayoutItemSchedulingContext request,
        CancellationToken cancellationToken)
    {
        await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);

        string serializedContext = await dbContext.PlayoutItems
            .AsNoTracking()
            .Where(pi => pi.Id == request.PlayoutItemId)
            .Select(pi => pi.SchedulingContext)
            .SingleOrDefaultAsync(cancellationToken);

        if (string.IsNullOrWhiteSpace(serializedContext))
        {
            return Option<string>.None;
        }

        // Decode/enrich exactly the way the troubleshooting decode path does, reusing the
        // single ProcessSchedulingContext handler so any future format change stays in one place.
        return await mediator.Send(new ProcessSchedulingContext(serializedContext), cancellationToken);
    }
}
