using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Sites.Commands.UpdateSite; using Heimdall.Application.Tests.Common; using Heimdall.Domain.Entities; using Microsoft.EntityFrameworkCore; using NSubstitute; namespace Heimdall.Application.Tests.Handlers.Sites; public class UpdateSiteHandlerTests { private readonly Site _existingSite = new("Original Name", "Original Address", "Europe/Paris"); [Fact] public async Task Update_site_should_return_success() { var context = Substitute.For(); context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); var handler = new UpdateSiteHandler(context); var command = new UpdateSiteCommand(_existingSite.Id, "Updated Name", "New Address", "America/New_York"); var result = await handler.Handle(command, CancellationToken.None); result.IsSuccess.ShouldBeTrue(); result.Data.ShouldNotBeNull(); result.Data.Name.ShouldBe("Updated Name"); result.Data.Address.ShouldBe("New Address"); result.Data.Timezone.ShouldBe("America/New_York"); } [Fact] public async Task Update_nonexistent_site_should_return_not_found() { var context = Substitute.For(); context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); var handler = new UpdateSiteHandler(context); var command = new UpdateSiteCommand(Guid.NewGuid(), "Name", null, null); var result = await handler.Handle(command, CancellationToken.None); result.IsSuccess.ShouldBeFalse(); result.StatusCode.ShouldBe(404); } [Fact] public async Task Update_site_should_call_save_changes() { var context = Substitute.For(); context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); var handler = new UpdateSiteHandler(context); var command = new UpdateSiteCommand(_existingSite.Id, "Updated", null, null); await handler.Handle(command, CancellationToken.None); await context.Received(1).SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); } [Fact] public async Task Update_site_should_record_actor_and_old_new_values() { var actorId = Guid.NewGuid(); AuditLog? entry = null; var context = Substitute.For(); context.Sites.Returns(MockDbSetHelper.CreateFor([_existingSite])); var auditLogs = Substitute.For>(); auditLogs.When(set => set.Add(Arg.Any())).Do(call => entry = call.Arg()); context.AuditLogs.Returns(auditLogs); await new UpdateSiteHandler(context).Handle( new UpdateSiteCommand(_existingSite.Id, "Updated Name", "New Address", "America/New_York", ActorId: actorId), CancellationToken.None); entry.ShouldNotBeNull(); entry.UserId.ShouldBe(actorId); entry.OldValue!.ShouldContain("Original Name"); entry.NewValue!.ShouldContain("Updated Name"); } }