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

namespace TeleWave.Application.Library.Genres.UpdateGenre;

public sealed class UpdateGenreCommandHandler(IAppDbContext dbContext)
    : ICommandHandler<UpdateGenreCommand, Result>
{
    public async Task<Result> Handle(
        UpdateGenreCommand command,
        CancellationToken cancellationToken
    )
    {
        var genre = await dbContext
            .Genres.Include(g => g.Aliases)
            .FirstOrDefaultAsync(g => g.Id == command.GenreId, cancellationToken);
        if (genre is null)
            return Result.Failure(GenreErrors.NotFound);

        var aliases = GenreAliasInput.Collect(command.Name, genre.Slug, command.Aliases);

        // Псевдоним уникален по всему справочнику — проверяем, не занят ли он другим жанром.
        var taken = await dbContext
            .GenreAliases.Where(a => aliases.Contains(a.Value) && a.GenreId != genre.Id)
            .AnyAsync(cancellationToken);
        if (taken)
            return Result.Failure(GenreErrors.AliasTaken);

        genre.Rename(command.Name);
        genre.SetSortOrder(command.SortOrder);
        genre.ReplaceAliases(aliases);
        return Result.Success();
    }
}
