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

namespace TeleWave.Application.Library.Collections.DeleteCollection;

public sealed class DeleteCollectionCommandHandler(
    IAppDbContext dbContext,
    GroupMembershipCleaner groupCleaner
) : ICommandHandler<DeleteCollectionCommand, Result>
{
    public async Task<Result> Handle(
        DeleteCollectionCommand command,
        CancellationToken cancellationToken
    )
    {
        var collection = await dbContext.Collections.FirstOrDefaultAsync(
            c => c.Id == command.CollectionId,
            cancellationToken
        );
        if (collection is null)
            return Result.Failure(CollectionErrors.NotFound);

        // Ссылка группы полиморфна — каскад БД её не снимет.
        await groupCleaner.RemoveElementAsync(
            GroupElementKind.Collection,
            command.CollectionId,
            cancellationToken
        );

        dbContext.Collections.Remove(collection);
        return Result.Success();
    }
}
