using HelpDesk.Data.Repositories; using HelpDesk.Models.DTOs; using HelpDesk.Models.Entities; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace HelpDesk.API.Controllers; [ApiController] [Route("api/[controller]")] [Authorize(Policy = "Admin")] public class GroupsController : ControllerBase { private readonly IGroupRepository _groupRepository; public GroupsController(IGroupRepository groupRepository) { _groupRepository = groupRepository; } [HttpGet] public async Task>> GetGroups() { var groups = await _groupRepository.GetAllAsync(); return Ok(groups.Select(MapToDto)); } [HttpGet("{id}")] public async Task> GetGroup(Guid id) { var group = await _groupRepository.GetByIdAsync(id); if (group == null) return NotFound(new { error = "Group not found." }); return Ok(MapToDto(group)); } [HttpPost] public async Task> CreateGroup([FromBody] CreateGroupRequest request) { if (string.IsNullOrWhiteSpace(request.Name)) return BadRequest(new { error = "Name is required." }); var group = new Group { Name = request.Name, Description = request.Description, IsActive = true, CreatedAt = DateTime.UtcNow }; var created = await _groupRepository.CreateAsync(group); return CreatedAtAction(nameof(GetGroup), new { id = created.Id }, MapToDto(created)); } [HttpPut("{id}")] public async Task> UpdateGroup(Guid id, [FromBody] CreateGroupRequest request) { var group = await _groupRepository.GetByIdAsync(id); if (group == null) return NotFound(new { error = "Group not found." }); group.Name = request.Name; if (request.Description != null) group.Description = request.Description; var updated = await _groupRepository.UpdateAsync(group); if (updated == null) return StatusCode(500, new { error = "Failed to update group." }); return Ok(MapToDto(updated)); } [HttpDelete("{id}")] public async Task DeleteGroup(Guid id) { var deleted = await _groupRepository.DeleteAsync(id); if (!deleted) return NotFound(new { error = "Group not found." }); return NoContent(); } private static GroupDto MapToDto(Group g) => new() { Id = g.Id, Name = g.Name, Description = g.Description, IsActive = g.IsActive, CreatedAt = g.CreatedAt }; }