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 ProfessionalController : ControllerBase
    {
        private readonly IProfessionalDom _professionalService;

        public ProfessionalController(IProfessionalDom professionalService)
        {
            _professionalService = professionalService ?? throw new ArgumentNullException(nameof(professionalService));
        }

        [HttpGet("all")]
        public async Task<IActionResult> GetAll([FromQuery] int page = 1, [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _professionalService.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? fullname,
            [FromQuery] string? document,
            [FromQuery] string? type,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _professionalService.SearchAsync(fullname, document, type, 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<EProfessional>> GetById(int id)
        {
            try
            {
                var professional = await _professionalService.GetByIdAsync(id);
                if (professional == null)
                    return NotFound();

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

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

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

                var success = await _professionalService.UpdateAsync(professional);

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

                return Ok("Profesional 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] ProfessionalSearchParams searchParams)
        {
            try
            {
                var file = await _professionalService.ExportFilteredProfessionalsToExcelAsync(searchParams);
                return File(file,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "Profesionales.xlsx");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}
