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.API.Extensions;
using PARR.Constants;
using PARR.DAL.Contracts;
using PARR.DAL.DomainModels;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Рабочие группы
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class WorkGroupController : BaseApiController
    {
        private readonly IMapper mapper;
        private readonly IWorkGroupService workGroupService;

        public WorkGroupController(
            IMapper mapper,
            IWorkGroupService workGroupService
            )
        {
            this.mapper = mapper;
            this.workGroupService = workGroupService;
        }


        /// <summary>
        /// Список рабочих групп постранично
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.WorkGroup.GetAll)]
        public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery, [FromQuery] WorkGroupQuery filter)
        {
            var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);

            IQueryable<WorkGroup> query = workGroupService.Get()
                                                .Include(t => t.ResponseArea)
                                                .OrderBy(t => t.Name);

            if (!string.IsNullOrEmpty(filter.Name))
                query = query.Where(t => t.Name.ToLower().Contains(filter.Name.ToLower()));

            if (filter.ResponseAreaCode.HasValue)
            {
                //todo: validate ResponseAreaEnum
                if (!Enum.IsDefined(typeof(ResponseAreaEnum), filter.ResponseAreaCode.Value))
                    return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(filter.ResponseAreaCode), Message = "Неверное значение" } }));

                query = query.Where(t => t.ResponseAreaCode == filter.ResponseAreaCode.Value);
            }

            var workGroups = await workGroupService.GetPage(query, paginationFilter).ToListAsync();

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

            var workGroupResponse = mapper.Map<List<WorkGroupResponse>>(workGroups);
            var paginationResponse = new PagedResponse<WorkGroupResponse>(workGroupResponse, true).GetPaginatedProps(paginationFilter, query);

            return Ok(paginationResponse);
        }


        /// <summary>
        /// Получить рабочую группу по id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.WorkGroup.Get)]
        public async Task<IActionResult> Get([FromRoute] Guid id)
        {
            var workGroup = await workGroupService.Get().Include(t => t.ResponseArea).FirstOrDefaultAsync(t => t.Id == id);

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

            var response = mapper.Map<WorkGroupResponse>(workGroup);

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

    }
}
