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.Core.Repositories.Interfaces;
using PARR.Domain.Common.Pagination;
using PARR.Domain.Common.Roles;
using PARR.Domain.Entities;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// История изменения шаблонов
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class TemplateHistoryController : BaseApiController
    {
        private readonly IMapper mapper;
        private readonly ITemplateHistoryRepository templateHistoryService;

        public TemplateHistoryController(
            IMapper mapper,
            ITemplateHistoryRepository templateHistoryService
            )
        {
            this.mapper = mapper;
            this.templateHistoryService = templateHistoryService;
        }


        /// <summary>
        /// Получить историю изменения шаблонов постранично
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.TemplateHistory.GetAll)]
        public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery, [FromQuery] TemplateHistoryQuery requestQuery)
        {
            var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);

            IQueryable<TemplateHistory> query = templateHistoryService.Get()
                    .OrderByDescending(t => t.DateAddedToHistory);

            if (requestQuery.TemplateId.HasValue)
                query = query.Where(t => t.ParentId == requestQuery.TemplateId.Value);

            if (!string.IsNullOrEmpty(requestQuery.InitiatorIp))
                query = query.Where(t => t.InitiatorIp == requestQuery.InitiatorIp);

            if (requestQuery.ParrComponentId != null)
                query = query.Where(t => t.InitiatorParrComponentId == requestQuery.ParrComponentId);

            var history = await templateHistoryService.GetPage(query, paginationFilter).ToListAsync();

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

            var historyResponse = mapper.Map<List<TemplateHistoryResponse>>(history);
            var paginationResponse = new PagedResponse<TemplateHistoryResponse>(historyResponse, true).GetPaginatedProps(paginationFilter, query);

            return Ok(paginationResponse);
        }

    }
}
