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

namespace TeleWave.Application.Programming.Templates.Junctions;

public sealed class DeleteJunctionCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<DeleteJunctionCommand, Result>
{
    public async Task<Result> Handle(
        DeleteJunctionCommand command,
        CancellationToken cancellationToken
    )
    {
        var junction = await JunctionLoader.LoadAsync(
            dbContext,
            command.JunctionId,
            cancellationToken
        );
        if (junction is null)
            return Result.Failure(TemplateErrors.JunctionNotFound);

        // Слот, ссылающийся на удалённый стык, молча остался бы без врезок — проверяем заранее.
        var used = await dbContext.Slots.AnyAsync(
            s => s.JunctionBetweenId == junction.Id || s.JunctionAfterId == junction.Id,
            cancellationToken
        );
        if (used)
            return Result.Failure(TemplateErrors.JunctionInUse);

        dbContext.JunctionTemplates.Remove(junction);
        return await JunctionLoader.MarkTemplateChangedAsync(
            dbContext,
            junction,
            cancellationToken
        );
    }
}
