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

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

        public LSUnitOfMeasureController(ILSUnitOfMeasureDom service)
        {
            _service = service ?? throw new ArgumentNullException(nameof(service));
        }

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

        [HttpGet("GetById/{id}")]
        public async Task<IActionResult> GetById(int id)
        {
            var result = await _service.GetByIdAsync(id);
            return result is null ? NotFound() : Ok(result);
        }

        [HttpPost("Create")]
        public async Task<IActionResult> Create([FromBody] ELSUnitOfMeasure model)
        {
            try
            {
                var newId = await _service.AddAsync(model);
                return CreatedAtAction(nameof(GetById), new { id = newId }, model);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [HttpPut("Update")]
        public async Task<IActionResult> Update([FromBody] ELSUnitOfMeasure model)
        {
            try
            {
                await _service.UpdateAsync(model);
                return Ok();
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}
