using Core.Interfaces;
using Domain.Entities;
using Domain.Generics;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;

namespace phronCare.API.Controllers.Sales
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly IProductDom _productService;

        public ProductController(IProductDom productService)
        {
            _productService = productService ?? throw new ArgumentNullException(nameof(productService));
        }

        [HttpGet("all")]
        public async Task<IActionResult> GetAll([FromQuery] int page = 1, [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _productService.GetAllAsync(page, pageSize);
                return Ok(result);
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                return StatusCode(500, $"{methodName} Message: {ex.Message}");
            }
        }

        [HttpGet("search")]
        public async Task<IActionResult> Search(
            [FromQuery] string? term,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _productService.SearchAsync(term, page, pageSize);
                return Ok(result);
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                return StatusCode(500, $"{methodName} Message: {ex.Message}");
            }
        }

        [HttpGet("{id:int}")]
        public async Task<ActionResult<EProduct>> GetById(int id)
        {
            try
            {
                var product = await _productService.GetByIdAsync(id);
                if (product == null)
                    return NotFound();

                return Ok(product);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Error: {ex.Message}");
            }
        }

        [HttpPost("create")]
        public async Task<IActionResult> Create([FromBody] EProduct product)
        {
            try
            {
                if (product == null)
                    return BadRequest("El producto no puede ser nulo.");

                var result = await _productService.CreateAsync(product);
                return Ok(result);
            }
            catch (ArgumentNullException ex)
            {
                return BadRequest($"Validación fallida: {ex.Message}");
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest($"Error de negocio: {ex.Message}");
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                return StatusCode(500, $"{methodName} Message: {ex.Message}");
            }
        }

        [HttpPut("update")]
        public async Task<IActionResult> Update([FromBody] EProduct product)
        {
            try
            {
                if (product == null || product.Id <= 0)
                    return BadRequest("El producto es inválido o no tiene un ID válido.");

                var success = await _productService.UpdateAsync(product);

                if (!success)
                    return NotFound($"No se encontró un producto con ID {product.Id}.");

                return Ok("Producto actualizado correctamente.");
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                return StatusCode(500, $"{methodName} Message: {ex.Message}");
            }
        }

        [HttpPost("exportfiltered")]
        public async Task<IActionResult> ExportFiltered([FromBody] ProductSearchParams searchParams)
        {
            try
            {
                var file = await _productService.ExportFilteredProductsToExcelAsync(searchParams);
                return File(file,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "Productos.xlsx");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}
