using Heimdall.Application.DTOs; using Heimdall.Application.Groups.Commands.AddCameraToGroup; using Heimdall.Application.Groups.Commands.RemoveCameraFromGroup; using Heimdall.Application.Groups.Queries.GetCamerasByGroup; using Heimdall.Infrastructure.Security; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; namespace Heimdall.Api.Controllers; /// /// Group-Camera access management (Admin only). /// Allows assigning/revoking camera access to groups. /// [ApiController] [Route("api/groups/{groupId:guid}/cameras")] [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminUsers)] [EnableRateLimiting("Api")] public class GroupCamerasController : ControllerBase { private readonly IMediator _mediator; public GroupCamerasController(IMediator mediator) => _mediator = mediator; /// List all cameras a group has access to. [HttpGet] [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task List( Guid groupId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default) { var result = await _mediator.Send(new GetCamerasByGroupQuery(groupId, page, pageSize), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(result.Data); } /// Grant camera access to a group. [HttpPost] [ProducesResponseType(typeof(GroupCameraAccessResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(void), StatusCodes.Status409Conflict)] public async Task Create( Guid groupId, [FromBody] CreateGroupCameraAccessRequest request, CancellationToken ct = default) { if (request.GroupId != groupId) return BadRequest(new { error = "Group ID in body does not match route" }); if (!this.TryGetUserId(out var actorId)) return Unauthorized(); var command = new AddCameraToGroupCommand(request.GroupId, request.CameraId, actorId); var result = await _mediator.Send(command, ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(result.Data); } /// Revoke camera access from a group. [HttpDelete("{cameraId:guid}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Delete(Guid groupId, Guid cameraId, CancellationToken ct = default) { if (!this.TryGetUserId(out var actorId)) return Unauthorized(); var command = new RemoveCameraFromGroupCommand(groupId, cameraId, actorId); var result = await _mediator.Send(command, ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); return Ok(); } }