Files
Heimdall/src/Heimdall.Application/Sites/Commands/DeleteSite/DeleteSiteHandler.cs
T

51 lines
1.8 KiB
C#

using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Application.Sites.Commands.DeleteSite;
public class DeleteSiteHandler : IRequestHandler<DeleteSiteCommand, ServiceResult>
{
private readonly IApplicationDbContext _context;
public DeleteSiteHandler(IApplicationDbContext context) => _context = context;
public async Task<ServiceResult> Handle(DeleteSiteCommand request, CancellationToken cancellationToken)
{
var site = await _context.Sites.FindAsync([request.Id], cancellationToken).ConfigureAwait(false);
if (site is null)
return ServiceResult.NotFound("Site not found");
// ── Cascade soft-delete: agents + cameras in the same transaction ──
var cameras = await _context.Cameras
.Where(c => c.SiteId == request.Id && !c.IsDeleted)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
var agents = await _context.Agents
.Where(a => a.SiteId == request.Id && !a.IsDeleted)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
foreach (var camera in cameras)
camera.SoftDelete();
foreach (var agent in agents)
agent.SoftDelete();
// Soft-delete the site itself
site.SoftDelete();
// Audit log with cascade info
_context.AuditLogs.Add(new AuditLog(
null,
"Site.Deleted",
"Site",
request.Id.ToString(),
newValue: $"Cascade: {agents.Count} agent(s), {cameras.Count} camera(s) soft-deleted"));
await _context.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
return ServiceResult.Success();
}
}