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 CustomerController : ControllerBase
    {
        private readonly ICustomerDom _customerService;
        public CustomerController(ICustomerDom customerService)
        {
            _customerService = customerService ?? throw new ArgumentNullException(nameof(customerService));
        }
        
        [HttpGet("all")]
        public async Task<IActionResult> GetAll([FromQuery] int page = 1, [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _customerService.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? name,
            [FromQuery] string? email,
            [FromQuery] string? document,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _customerService.SearchAsync(name, email, document, 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<ECustomer>> GetById(int id)
        {
            try
            {
                var customer = await _customerService.GetByIdAsync(id);
                if (customer == null)
                    return NotFound();

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

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

                var result = await _customerService.CreateAsync(customer);
                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] ECustomer customer)
        {
            try
            {
                if (customer == null || customer.Id <= 0)
                    return BadRequest("El cliente es inválido o no tiene un ID válido.");

                var success = await _customerService.UpdateAsync(customer);

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

                return Ok("Cliente 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] CustomerSearchParams searchParams)
        {
            try { 
                var file = await _customerService.ExportFilteredCustomersToExcelAsync(searchParams);
                return File(file,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "Clientes.xlsx");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}
