using MediatR;
using Modules.Library.Application.Gateways;

namespace Modules.Library.Application.Commands.Dictionaries.Language;

public class SetLanguageNameCommand : IRequest<Unit>
{
    public Guid Id { get; set; } = default!;
    public string? Code { get; set; }
    public string? Name { get; set; }
}

public class SetLanguageNameCommandHandler(ILanguageGateway languageGateway) : IRequestHandler<SetLanguageNameCommand, Unit>
{
    public async Task<Unit> Handle(SetLanguageNameCommand request, CancellationToken cancellationToken)
    {
        var genre = await languageGateway.GetLanguageById(request.Id);
        if (string.IsNullOrWhiteSpace(string.Concat(request.Code?.Trim(), request.Name?.Trim()))) throw new Exception("Nothing to change");
        if (await languageGateway.IsLanguageExists(request.Code ?? genre.CodeIso2, request.Name ?? genre.Name, request.Id))
            throw new Exception("Language with the same name or code already exists");
        if (!string.IsNullOrWhiteSpace(request.Code) && request.Code.Trim().Length != 3) throw new Exception("Language code length must be 3");
        /*
        if (!string.IsNullOrWhiteSpace(request.Code) && request.Code.Trim().Length != 3)
            throw new Exception("Language code must be ISO 639-3 Alpha-3 code");
        */
        await languageGateway.Edit(request.Id, request.Code, request.Name);
        return Unit.Value;
    }
}