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 BusinessUnitController : ControllerBase
    {
        private readonly IBusinessUnitDom _businessUnitService;

        public BusinessUnitController(IBusinessUnitDom businessUnitService)
        {
            _businessUnitService = businessUnitService ?? throw new ArgumentNullException(nameof(businessUnitService));
        }

        [HttpGet("all")]
        public async Task<IActionResult> GetAll()
        {
            try
            {
                var result = await _businessUnitService.GetAllAsync();
                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)
        {
            try
            {
                var result = await _businessUnitService.SearchAsync(term ?? string.Empty);
                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<EBusinessUnit>> GetById(int id)
        {
            try
            {
                var result = await _businessUnitService.GetByIdAsync(id);
                if (result == null)
                    return NotFound($"No se encontró una unidad de negocio con ID {id}.");

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

        [HttpPost("create")]
        public async Task<IActionResult> Create([FromBody] EBusinessUnit unit)
        {
            try
            {
                if (unit == null)
                    return BadRequest("La unidad de negocio no puede ser nula.");

                var result = await _businessUnitService.CreateAsync(unit);
                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] EBusinessUnit unit)
        {
            try
            {
                if (unit == null || unit.Id <= 0)
                    return BadRequest("La unidad de negocio es inválida o no tiene un ID válido.");

                var success = await _businessUnitService.UpdateAsync(unit);

                if (!success)
                    return NotFound($"No se encontró una unidad de negocio con ID {unit.Id}.");

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

        [HttpDelete("{id:int}")]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                var success = await _businessUnitService.DeleteAsync(id);

                if (!success)
                    return NotFound($"No se encontró una unidad de negocio con ID {id}.");

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