using Contracts;
using Microsoft.AspNetCore.Mvc;
using Services.Abstractions;

namespace Presentation.Controllers
{
    [ApiController]
    [Route("api/regions")]
    public class RegionController : ControllerBase
    {
        private readonly IRegionService _regionService;
        public RegionController(IRegionService regionService)
        {
            _regionService = regionService;
        }
        [HttpGet]
        public async Task<IActionResult> GetAllAsync()
        {
            var regions = await _regionService.GetAllAsync();
            return Ok(regions);
        }
        [HttpGet("{id:guid}")]
        public async Task<IActionResult> GetByIdAsync(Guid id)
        {
            var region = await _regionService.GetByIdAsync(id);
            if (region == null)
            {
                return NotFound("Регион не найден.");
            }
            return Ok(region);
        }
        [HttpPost]
        public async Task<IActionResult> CreateAsync([FromBody] RegionDtoForCreate regionDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var newRegion = await _regionService.CreateAsync(regionDto);
            return Ok(newRegion);
        }
        [HttpPut("{id:guid}")]
        public async Task<IActionResult> UpdateAsync(Guid id, [FromBody] RegionDtoForUpdate regionDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                await _regionService.UpdateAsync(id, regionDto);
            }
            catch (KeyNotFoundException)
            {
                return NotFound("Регион не найден.");
            }

            return NoContent();
        }
        [HttpDelete("{id:guid}")]
        public async Task<IActionResult> DeleteAsync(Guid id)
        {
            try
            {
                await _regionService.DeleteAsync(id);
            }
            catch (KeyNotFoundException)
            {
                return NotFound("Регион не найден.");
            }

            return NoContent();
        }

    }
}