using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using PSTW_CentralSystem.DBContext; using PSTW_CentralSystem.Models; using System.ComponentModel.DataAnnotations; namespace PSTW_CentralSystem.Controllers.API { [ApiController] [Route("[controller]")] [Authorize] public class RoleAPI : Controller { private readonly ILogger _logger; private readonly IdentityDBContext _authDbContext; private readonly RoleManager _roleManager; public RoleAPI(ILogger logger, IdentityDBContext authDbContext, RoleManager roleManager) { _logger = logger; _authDbContext = authDbContext; _roleManager = roleManager; } [HttpPost("GetRoleList")] public async Task GetRoleList() { var roles = await _roleManager.Roles.Select(r => new { r.Id, r.Name, r.Description }).Where(r => r.Name != "SuperAdmin" && r.Name != "SystemAdmin").ToListAsync(); return Json(roles); } [HttpPost("AddRole")] public async Task AddRole([FromBody] RoleInput newRole) { try { await _roleManager.CreateAsync(new RoleModel { Name = newRole.newRoleName, Description = newRole.newRoleDescription ?? null }); return Ok(new { message = "Role added successfully", newRole = newRole.newRoleName }); } catch (Exception ex) { return StatusCode(500, new { message = $"An error occurred: {ex.Message}" }); } } [HttpDelete("DeleteRole/{id}")] public async Task DeleteRole(string id) { var role = await _roleManager.FindByIdAsync(id); if (role == null) { return NotFound(new { message = "Role not found" }); } await _roleManager.DeleteAsync(role); return Ok(new { message = "Role deleted successfully" }); } } public class RoleInput { [Required] public string? newRoleName { get; set; } public string? newRoleDescription { get; set; } } }