using HrynCo.NotificationService.DAL.Abstract.Repositories; using HrynCo.NotificationService.DAL.Abstract.Templates; using HrynCo.NotificationService.Services.Core; using HrynCo.NotificationService.Services.Logging; using static HrynCo.NotificationService.Services.Core.ServiceResultHelper; namespace HrynCo.NotificationService.Services.TemplateDefinitions; internal sealed class DeleteUnusedServiceLanguageHandler( IContextualSerilogLogger logger, INotificationServiceRepository services) : RequestHandler>(logger) { protected override async Task> DoOnHandle(DeleteUnusedServiceLanguageCommand request, CancellationToken cancellationToken) { if (request.Revision == Guid.Empty) return Failure("A nonempty service revision is required.", ServiceErrorCode.InvalidRequest); var service = await services.GetAsync(request.ServiceId, cancellationToken); var language = service?.Languages.SingleOrDefault(l => l.Id == request.LanguageId); if (language is null) return Failure("Service language not found.", ServiceErrorCode.NotFound); if (language.VersionCount > 0) return Failure("This language has template versions. Use delete-with-versions with explicit confirmation and the current count.", ServiceErrorCode.Conflict); try { // The repository repeats the zero-count and revision checks under its mutation lock. await services.RemoveLanguageAsync(request.ServiceId, request.LanguageId, 0, request.Revision, cancellationToken); return Success(Unit.Value); } catch (EmailTemplateWriteException error) { return Failure(error.Message, error.IsConflict ? ServiceErrorCode.Conflict : ServiceErrorCode.InvalidRequest); } } }