using LSFE.Domain.Contracts;
using LSFE.Domain.Services;
using LSFE.Infrastructure.Dto.Maintenance;
using LSFE.Infrastructure.Entities.Maintenance;
using LSFE.Infrastructure.Model;
using Microsoft.AspNetCore.Mvc;


namespace LSFE.API.Controllers
{
    public class InventoryController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ExcelInventoryService _excelService;
        public InventoryController(IUnitOfWork unitOfWork, IWebHostEnvironment env, 
            ExcelInventoryService excelService)
            : base(unitOfWork, env)
        {
            _unitOfWork = unitOfWork;
            _excelService = excelService;
        }

        #region Post Put
        [HttpPost("UploadExcel")]
        public async Task<IActionResult> UploadExcel([FromForm] UploadExcelDto request)
        {
            if (request.File == null || request.File.Length == 0)
                return BadRequest("No file uploaded");

            var allowedExtensions = new[] { ".xlsx", ".xls" };
            var extension = Path.GetExtension(request.File.FileName).ToLowerInvariant();

            if (!allowedExtensions.Contains(extension))
                return BadRequest("Invalid file type. Only Excel files (.xlsx, .xls) are allowed");

            if (request.File.Length > 20 * 1024 * 1024) // 20MB
                return BadRequest("File size exceeds 20MB limit");

            var result = await _excelService.ProcessExcelFileAsync(request.File, request.UserId, request.UserName);

            if (!result.Success)
                return BadRequest(result);

            return Ok(result);
        }
        public class UploadExcelDto
        {
            [FromForm(Name = "file")]
            public IFormFile? File { get; set; }

            [FromForm(Name = "userId")]
            public string? UserId { get; set; }

            [FromForm(Name = "userName")]
            public string? UserName { get; set; }
        }

        [HttpPost("PostPutInventory")]
        public async Task<IActionResult> PostPutInventory([FromBody] Inventory dto)
        {
            if (dto == null)
                return BadRequest("Invalid inventory data.");

            var response = await _unitOfWork.Inventory.AddOrUpdateAsync(dto);
            if (response.Success)
            {
                await _unitOfWork.SaveChangesAsync();
                return Ok(response);
            }

            return BadRequest(response);
        }
        [HttpDelete("DeleteInventory")]
        public async Task<IActionResult> DeleteAsync([FromQuery] InventoryDto dto)
        {
            var result = new Response();

            if (dto.UserRole != "ADMIN" && dto.UserRole != "DSM")
            {
                result.Success = false;
                result.MessCode = 0;
                result.Message = "You do not have permission to delete this item.";
                return BadRequest(result);
            }

            var isUsing = await _unitOfWork.InventoryTransactions.FindAsync(i =>
                i.InventoryId == dto.InventoryId &&
                i.IsActive == true
            );

            if (isUsing != null)
            {
                result.Success = false;
                result.MessCode = 0;
                result.Message = "This item cannot be deleted because some quantities are already used or allocated.";
                return BadRequest(result);
            }

            result = await _unitOfWork.Inventory.DeleteAsync(dto.InventoryId);

            if (!result.Success)
                return BadRequest(result);

            return Ok(result);
        }

        #endregion

        #region Get
        [HttpGet("inventory")]
        public async Task<IActionResult> GetInventory([FromQuery] InventoryDto dto)
        {
            var inventory = await _unitOfWork.Inventory.GetAllAsync();
            var filtered = dto.UserRole == "ADMIN" || dto.UserRole == "DSM"
             ? inventory.Where(i => i.IsActive)
             : inventory.Where(i => i.IsActive && i.MedRepName == dto.UpdatedBy);

            return Ok(filtered);
        }
        #endregion
    }
}
