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

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Управление приложениями
    /// </summary>

    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class ApplicationController : BaseApiController
    {
        private readonly IMapper mapper;
        private readonly IApplicationService applicationService;

        public ApplicationController(
            IMapper mapper,
            IApplicationService applicationService
            )
        {
            this.mapper = mapper;
            this.applicationService = applicationService;
        }


        /// <summary>
        /// Список приложений постранично
        /// </summary>
        /// <param name="paginationQuery"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Application.GetAll)]
        public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery, [FromQuery] ApplicationQuery filter)
        {
            var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);

            IQueryable<Application> query = applicationService.Get()
                                        .Include(t => t.ApplicationType)
                                        .OrderBy(t => t.Name);

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

            if (filter.TypeId.HasValue)
                query = query.Where(t => t.ApplicationTypeId == filter.TypeId);

            if (filter.Id.HasValue)
                query = query.Where(t => t.Id == filter.Id);


            var apps = await applicationService.GetPage(query, paginationFilter).ToListAsync();

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

            var appsResponse = mapper.Map<List<ApplicationResponse>>(apps);
            var paginationResponse = new PagedResponse<ApplicationResponse>(appsResponse, true).GetPaginatedProps(paginationFilter, query);

            return Ok(paginationResponse);
        }
    }
}
