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 PeopleController : ControllerBase
    {
        private readonly IPeopleDom _peopleService;

        public PeopleController(IPeopleDom peopleService)
        {
            _peopleService = peopleService ?? throw new ArgumentNullException(nameof(peopleService));
        }

        #region Get Methods

        [HttpGet("all")]
        public async Task<IActionResult> GetAll([FromQuery] int page = 1, [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _peopleService.GetAllAsync(page, pageSize);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return InternalError(ex);
            }
        }

        [HttpGet("{id:int}")]
        public async Task<IActionResult> GetById(int id)
        {
            try
            {
                var person = await _peopleService.GetByIdAsync(id);
                return person == null ? NotFound() : Ok(person);
            }
            catch (Exception ex)
            {
                return InternalError(ex);
            }
        }

        [HttpGet("search")]
        public async Task<IActionResult> SearchAsync([FromQuery] string? name, [FromQuery] string? email, [FromQuery] int page = 1, [FromQuery] int pageSize = 10)
        {
            try
            {
                var result = await _peopleService.SearchAsync(name, email, page, pageSize);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return InternalError(ex);
            }
        }

        #endregion

        #region Post/Put/Delete Methods

        [HttpPost("create")]
        public async Task<IActionResult> Create([FromBody] EPerson person)
        {
            try
            {
                if (person == null)
                    return BadRequest("La persona no puede ser nula.");

                var result = await _peopleService.AddAsync(person);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return InternalError(ex);
            }
        }

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

                var success = await _peopleService.UpdateAsync(person);
                return success ? Ok("Persona actualizada correctamente.") : NotFound($"No se encontró la persona con ID {person.Id}.");
            }
            catch (Exception ex)
            {
                return InternalError(ex);
            }
        }

        [HttpDelete("delete/{id:int}")]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                var success = await _peopleService.DeleteAsync(id);
                return success ? Ok("Persona eliminada correctamente.") : NotFound($"No se encontró la persona con ID {id}.");
            }
            catch (Exception ex)
            {
                return InternalError(ex);
            }
        }

        [HttpPost("exportfiltered")]
        public async Task<IActionResult> ExportFilteredPeople([FromBody] PeopleSearchParams searchParams)
        {
            try
            {
                var file = await _peopleService.ExportFilteredCustomersToExcelAsync(searchParams);
                return File(file,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "Vendedores.xlsx");
            }
            catch (Exception ex)
            {
                return InternalError(ex);
            }
        }

        #endregion

        #region Helpers

        private IActionResult InternalError(Exception ex)
        {
            var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
            return StatusCode(500, $"{methodName} Message: {ex.Message}");
        }

        #endregion
    }
}
