using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Domain.Common.Roles;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Справочник полей
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class UnitFieldController : BaseApiController
    {
        private readonly IUnitFieldRepository unitFieldService;
        private readonly IMapper mapper;

        public UnitFieldController(
            IUnitFieldRepository unitFieldService,
            IMapper mapper
            )
        {
            this.unitFieldService = unitFieldService;
            this.mapper = mapper;
        }

        /// <summary>
        /// Список доступных в БД атрибутов ЭК
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.UnitField.GetAll)]
        public async Task<IActionResult> GetAll()
        {
            var unitFields = await unitFieldService.Get()
                                    .OrderBy(t => t.AihitName)
                                    .ToListAsync();

            if (!unitFields.Any())
                return NoContent();

            var response = mapper.Map<List<FieldResponse>>(unitFields);

            return Ok(new Response<List<FieldResponse>>(response, true));
        }

        /// <summary>
        /// Получить имя атрибута по Id
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.UnitField.Get)]
        public async Task<IActionResult> Get([FromRoute] Guid id)
        {
            var unitField = await unitFieldService.Get().FirstOrDefaultAsync(t => t.Id == id);

            if (unitField == null)
                return NoContent();

            var response = mapper.Map<FieldResponse>(unitField);

            return Ok(new Response<FieldResponse>(response, true));
        }
    }
}
