using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PSTW_CentralSystem.DBContext;
using PSTW_CentralSystem.Models;
using System.Reflection;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

namespace PSTW_CentralSystem.Controllers.API
{
    [ApiController]
    [Route("[controller]")]

    public class AdminAPI : Controller
    {
        private readonly ILogger<AdminAPI> _logger;
        private readonly IdentityDBContext _authDbContext;
        private readonly UserManager<UserModel> _userManager;
        private readonly SignInManager<UserModel> _signInManager;

        public AdminAPI(ILogger<AdminAPI> logger, IdentityDBContext authDbContext, UserManager<UserModel> userManager, SignInManager<UserModel> signInManager)
        {
            _logger = logger;
            _authDbContext = authDbContext;
            _userManager = userManager;
            _signInManager = signInManager;
        }

        [HttpPost("GetClassAndMethodInformation")]
        public async Task<IActionResult> GetClassAndMethodInformation(string moduleName)
        {
            var controllerAndMethodList = new object();

            // Get the assembly containing the controllers
            var assembly = Assembly.GetExecutingAssembly();

            // Get all types in the assembly (controllers will typically be in the "Controllers" namespace)
            //var controllerTypes = await Task.Run(() => assembly.GetTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type) && type.IsClass && type.CompanyName.Contains("Controller") && type.CompanyName != "AdminController") .ToList());
            var controllerTypes = await Task.Run(() => assembly.GetTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type) && !type.Name.Contains("API") && type.IsClass && type.Name.Contains(moduleName)).FirstOrDefault());

            // Iterate over the controller types and get their methods
                var methods = controllerTypes?.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                    .Where(m => m.DeclaringType == controllerTypes) // Filter methods declared directly in the controller (ignoring inherited ones)
                    .Select(m => m.Name) // Get the method names
                    .ToList();

                controllerAndMethodList = (new
                {
                    Controller = controllerTypes?.Name,
                    Methods = methods
                });

            // Return the list as JSON
            return Json(controllerAndMethodList);
        }

        [HttpPost("GetListClassAndMethodInformation")]
        public async Task<IActionResult> GetListClassAndMethodInformation()
        {
            var controllerAndMethodList = new List<object>();

            // Get the assembly containing the controllers
            var assembly = Assembly.GetExecutingAssembly();

            // Get all types in the assembly (controllers will typically be in the "Controllers" namespace)
            //var controllerTypes = await Task.Run(() => assembly.GetTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type) && type.IsClass && type.CompanyName.Contains("Controller") && type.CompanyName != "AdminController") .ToList());
            var controllerTypes = await Task.Run(() => assembly.GetTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type) && type.IsClass && !type.Name.Contains("API") && !type.Name.Contains("Admin")).ToList());

            // Iterate over the controller types and get their methods
            foreach (var controllerType in controllerTypes) { 
                var methods = controllerType?.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                    .Where(m => m.DeclaringType == controllerType) // Filter methods declared directly in the controller (ignoring inherited ones)
                    .Select(m => m.Name) // Get the method names
                    .ToList();
            
            controllerAndMethodList.Add(new
                {
                    Controller = controllerType?.Name.Replace("Controller", string.Empty),
                    Methods = methods
                });
            }
            // Return the list as JSON
            return Json(controllerAndMethodList);
        }
        [HttpPost("GetUserList")]
        public async Task<IActionResult> GetUserList()
        {
            try
            {
                var user = await _userManager.GetUserAsync(User);

                var userRole = await _userManager.GetRolesAsync(user??new UserModel());
                List<UserModel> userInfo = new List<UserModel>();

                    // Fetch all users excluding those with roles SuperAdmin or SystemAdmin
                    var allUsers = await _authDbContext.Users
                        .Include(u => u.Department)
                        .ToListAsync();

                if (userRole == null || userRole.Count == 0)
                {
                    foreach (var u in allUsers)
                    {
                        var roles = await _userManager.GetRolesAsync(u);
                        if (!roles.Contains("SuperAdmin") && !roles.Contains("SystemAdmin"))
                        {
                            userInfo.Add(u);
                        }
                    }
                }
                else 
                { 
                    userInfo = await _authDbContext.Users.Include(u => u.Department).ToListAsync(); 
                }
                var userList = userInfo.Select(u => new 
                { 
                    id = u.Id, 
                    email = u.NormalizedEmail, 
                    company = u.Department?.Company?.CompanyName, 
                    department = u.Department,
                    role = _userManager.GetRolesAsync(u).Result
                }).ToList();
                return Ok(new { UserInfo = userList });
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"An error occurred: {ex.Message}");
            }
        }
    }
}
