using Core.Interfaces.Stock;
using Domain.Entities;
using Microsoft.AspNetCore.Mvc;

namespace phronCare.API.Controllers.Stock
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductDivisionController : ControllerBase
    {
        private readonly ILSProductDivisionDom _service;

        public ProductDivisionController(ILSProductDivisionDom service)
        {
            _service = service ?? throw new ArgumentNullException(nameof(service));
        }

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

        [HttpGet("GetById/{id}")]
        public async Task<IActionResult> GetById(int id)
        {
            var result = await _service.GetByIdAsync(id);
            if (result == null)
                return NotFound($"No se encontró una división con ID {id}.");

            return Ok(result);
        }

        [HttpGet("Search")]
        public async Task<IActionResult> Search([FromQuery] string? term, [FromQuery] int page = 1, [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _service.SearchAsync(term, page, pageSize);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [HttpPost("Create")]
        public async Task<IActionResult> Create([FromBody] ELSProductDivision division)
        {
            try
            {
                var created = await _service.CreateAsync(division);
                return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [HttpPut("Update")]
        public async Task<IActionResult> Update([FromBody] ELSProductDivision division)
        {
            try
            {
                var updated = await _service.UpdateAsync(division);
                return updated ? Ok() : NotFound($"No se encontró una división con ID {division.Id}.");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [HttpDelete("Delete/{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                var deleted = await _service.DeleteAsync(id);
                return deleted ? Ok() : NotFound($"No se encontró una división con ID {id}.");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}
