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

namespace TeleWave.Application.Programming.Groups.ExcludeGroupElement;

public sealed class ExcludeGroupElementCommandHandler(
    IAppDbContext dbContext,
    GroupStatsService stats
) : ICommandHandler<ExcludeGroupElementCommand, Result>
{
    public async Task<Result> Handle(
        ExcludeGroupElementCommand command,
        CancellationToken cancellationToken
    )
    {
        var group = await dbContext
            .Groups.Include(g => g.Items)
            .FirstOrDefaultAsync(g => g.Id == command.GroupId, cancellationToken);
        if (group is null)
            return Result.Failure(GroupErrors.NotFound);

        if (group.Mode != GroupMode.Dynamic)
            return Result.Failure(GroupErrors.ExclusionsForDynamicOnly);

        if (command.Excluded)
            group.Exclude(command.ElementKind, command.ElementId);
        else
            group.RemoveExclusion(command.ElementKind, command.ElementId);

        await stats.RecomputeAsync(group, cancellationToken);
        return Result.Success();
    }
}
