using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.Constants;
using PARR.DAL.DomainModels;
using PARR.DAL.Services.Interfaces;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Зоны ответственности
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class ResponseAreaController : BaseApiController
    {
        private readonly IMapper mapper;
        private readonly IResponseAreaService responseAreaService;

        public ResponseAreaController(
                IMapper mapper,
                IResponseAreaService responseAreaService
            )
        {
            this.mapper = mapper;
            this.responseAreaService = responseAreaService;
        }


        /// <summary>
        /// Список зон ответственности
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.ResponseArea.GetAll)]
        public async Task<IActionResult> GetAll()
        {
            var query = responseAreaService.Get().OrderBy(t => t.Name);

            var responseAreas = await query.ToListAsync();

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

            var response = mapper.Map<List<ResponseAreaResponse>>(responseAreas);

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


        /// <summary>
        /// Получить зону ответственности по коду
        /// </summary>
        /// <param name="responseAreaCode"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.ResponseArea.Get)]
        public async Task<IActionResult> Get([FromRoute] int responseAreaCode)
        {
            var responseArea = await responseAreaService.Get().FirstOrDefaultAsync(t => t.Code == responseAreaCode);

            if (responseArea == null)
                return NotFound();

            var response = mapper.Map<ResponseAreaResponse>(responseArea);

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