using HrynCo.NotificationService.DAL.Abstract.Templates; using HrynCo.DAL.Abstract; using HrynCo.NotificationService.DAL.Abstract.Repositories; using HrynCo.NotificationService.Services.Core; using HrynCo.NotificationService.Services.Logging; using static HrynCo.NotificationService.Services.Core.ServiceResultHelper; namespace HrynCo.NotificationService.Services.EmailTemplates.Delete; internal sealed class DeleteEmailTemplateHandler : RequestHandler> { private readonly IEmailTemplateRepository _templates; public DeleteEmailTemplateHandler( IContextualSerilogLogger logger, IEmailTemplateRepository templates) : base(logger) { _templates = templates; } protected override async Task> DoOnHandle( DeleteEmailTemplateCommand request, CancellationToken cancellationToken) { var template = await _templates.GetAsync( request.ServiceName, request.Key, request.LanguageCode, cancellationToken); if (template is null) return Failure("Template not found.", ServiceErrorCode.NotFound); if (request.ExpectedVersionId is Guid expectedId && template.Id != expectedId) return Failure("Template changed after you opened it. Reload before deleting.", ServiceErrorCode.Conflict); try { await _templates.DeleteAsync(template, cancellationToken); } catch (EmailTemplateWriteException error) { return Failure(error.Message, error.IsConflict ? ServiceErrorCode.Conflict : ServiceErrorCode.InvalidRequest); } return Success(Unit.Value); } }