using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PSTW_CentralSystem.Areas.Inventory.Models;
using PSTW_CentralSystem.DBContext;
using PSTW_CentralSystem.Models;

namespace PSTW_CentralSystem.Controllers.API
{
    [ApiController]
    [Route("[controller]")]
    public class ModuleAPI : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly CentralSystemContext _authDbContext;
        public ModuleAPI(ILogger<HomeController> logger, CentralSystemContext authDbContext)
        {
            _logger = logger;
            _authDbContext = authDbContext;
        }

        [HttpPost("GetModuleInformation")]
        public async Task<IActionResult> GetModuleInformation()
        {
            var qcList = await _authDbContext.ModuleSettings.ToListAsync();
            return Json(qcList);
        }

        [HttpPost("GetXModuleInformation")]
        public async Task<IActionResult> GetXModuleInformation(int? id)
        {
            var qcList = await _authDbContext.ModuleSettings.Where(x => x.SettingId == id).FirstOrDefaultAsync();
            return Json(qcList);
        }

        [HttpPost("AddMethod")]
        public async Task<IActionResult> AddMethod(int? id, string? module)
        {

            // Retrieve the module setting from the database
            var moduleSetting = await _authDbContext.ModuleSettings
                .Where(x => x.SettingId == id)
                .FirstOrDefaultAsync();

            if (moduleSetting == null)
            {
                return NotFound("Module setting not found");
            }

            // Initialize the list if null
            if (moduleSetting.MethodAllowedUserType == null)
            {
                moduleSetting.MethodAllowedUserType = new List<MethodAllowedUserType>();
            }

            // Add the new module
            moduleSetting.MethodAllowedUserType.Add(new MethodAllowedUserType
            {
                MethodName = module,
                AllowedUserTypesArray = Array.Empty<string>() 
            });

            // Save the changes to the database
            _authDbContext.ModuleSettings.Update(moduleSetting);
            await _authDbContext.SaveChangesAsync();

            return Json(moduleSetting);
        }


        [HttpPost("SaveData")]
        public async Task<IActionResult> SaveData([FromBody] ModuleSettingModel modelSettingList)
        {
            var qcList = await _authDbContext.ModuleSettings
                .Where(x => x.SettingId == modelSettingList.SettingId)
                .FirstOrDefaultAsync();

            if (qcList != null)
            {

                qcList.ModuleName = modelSettingList.ModuleName;
                qcList.AllowedUserType = modelSettingList.AllowedUserType;

                if (modelSettingList.MethodAllowedUserType != null)
                {
                    qcList.MethodAllowedUserType = modelSettingList.MethodAllowedUserType
                        .Select(m => new MethodAllowedUserType
                        {
                            MethodName = m.MethodName,
                            AllowedUserTypesArray = m.AllowedUserTypesArray
                        }).ToList();
                }

                qcList.ModuleStatus = modelSettingList.ModuleStatus;
                qcList.Description = modelSettingList.Description;

                _authDbContext.ModuleSettings.Update(qcList);
                await _authDbContext.SaveChangesAsync();
            }

            return Json(qcList);
        }

        [HttpPost("AddModule")]
        public async Task<IActionResult> AddModule([FromBody] ModuleSettingModel module)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            if (module == null)
            {
                return NotFound("Module is null");
            }

            try
            {
                _authDbContext.ModuleSettings.Add(module);
                await _authDbContext.SaveChangesAsync();
                var updatedList = await _authDbContext.ModuleSettings.ToListAsync();
                return Json(updatedList);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        
        [HttpPost("DeleteModule/{id}")]
        public async Task<IActionResult> DeleteModule(int? id)
        {
            if (id == null)
            {
                return NotFound("Module is null");
            }
            var moduleSetting = await _authDbContext.ModuleSettings.FindAsync(id);
            if (moduleSetting == null)
            {
                return NotFound("Module not found");
            }
            try
            {
                _authDbContext.ModuleSettings.Remove(moduleSetting!);
                await _authDbContext.SaveChangesAsync();
                var updatedList = await _authDbContext.ModuleSettings.ToListAsync();
                return Json(updatedList);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}
