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<RoleAPI> _logger;
        private readonly CentralSystemContext _centralDbContext;
        private readonly RoleManager<RoleModel> _roleManager;

        public RoleAPI(ILogger<RoleAPI> logger, CentralSystemContext centralDbContext, RoleManager<RoleModel> roleManager)
        {
            _logger = logger; 
            _centralDbContext = centralDbContext;
            _roleManager = roleManager;
        }

        [HttpPost("GetRoleList")]
        public async Task<IActionResult> 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<IActionResult> 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<IActionResult> 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; }
    }
}
