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

namespace phronCare.API.Controllers.Sales
{
    [Route("api/[controller]")]
    [ApiController]
    public class InstitutionController : ControllerBase
    {
        private readonly IInstitutionDom _institutionService;
        public InstitutionController(IInstitutionDom institutionService)
        {
            _institutionService = institutionService ?? throw new ArgumentNullException(nameof(institutionService));
        }
        [HttpGet("all")]
        public async Task<IActionResult> GetAll([FromQuery] int page = 1, [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _institutionService.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? type,
            [FromQuery] string? province,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _institutionService.SearchAsync(name, type, province, 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<EInstitution>> GetById(int id)
        {
            try
            {
                var institution = await _institutionService.GetByIdAsync(id);
                if (institution == null)
                    return NotFound();

                return Ok(institution);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Error: {ex.Message}");
            }
        }
        [HttpPost("create")]
        public async Task<IActionResult> Create([FromBody] EInstitution institution)
        {
            try
            {
                if (institution == null)
                    return BadRequest("La institución no puede ser nula.");

                var result = await _institutionService.CreateAsync(institution);
                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] EInstitution institution)
        {
            try
            {
                if (institution == null || institution.Id <= 0)
                    return BadRequest("La institución es inválida o no tiene un ID válido.");

                var success = await _institutionService.UpdateAsync(institution);

                if (!success)
                    return NotFound($"No se encontró una institución con ID {institution.Id}.");

                return Ok("Institución actualizada 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] InstitutionSearchParams searchParams)
        {
            try
            {
                var file = await _institutionService.ExportFilteredInstitutionsToExcelAsync(searchParams);
                return File(file,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "Instituciones.xlsx");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}
