using System.Security.Claims; using FastEndpoints; using Microsoft.EntityFrameworkCore; using TrackQrApi.Data; using TrackQrApi.Features.Auth.Common; namespace TrackQrApi.Features.Domains.Endpoints; public class DeleteDomainRequest { public Guid WorkspaceId { get; set; } public Guid Id { get; set; } } public class DeleteDomainEndpoint(AppDbContext db) : Endpoint { public override void Configure() { Delete("/workspaces/{WorkspaceId}/domains/{Id}"); } public override async Task HandleAsync(DeleteDomainRequest req, CancellationToken ct) { var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!); var domain = await db.Domains .Include(d => d.Workspace) .FirstOrDefaultAsync( d => d.Id == req.Id && d.WorkspaceId == req.WorkspaceId && d.Workspace.OwnerUserId == userId, ct); if (domain is null) { await HttpContext.Response.SendAsync(new MessageResponse("Domain not found"), 404, cancellation: ct); return; } // Check if any links are using this domain var linksUsingDomain = await db.ShortLinks .AnyAsync(l => l.DomainId == domain.Id, ct); if (linksUsingDomain) { await HttpContext.Response.SendAsync( new MessageResponse("Cannot delete domain: it has associated short links"), 400, cancellation: ct); return; } db.Domains.Remove(domain); await db.SaveChangesAsync(ct); await HttpContext.Response.SendAsync(new MessageResponse("Domain deleted"), cancellation: ct); } }