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

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

        public PatientController(IPatientDom patientService)
        {
            _patientService = patientService ?? throw new ArgumentNullException(nameof(patientService));
        }

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

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

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

                var result = await _patientService.CreateAsync(patient);
                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 BadRequest($"Error de negocio: {ex.Message}");
            }
        }

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

                var success = await _patientService.UpdateAsync(patient);

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

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

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