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.Contracts.V1.Responses.Statistics;
using PARR.API.Controllers.V1.Base;
using PARR.Core.Repositories.Interfaces;
using PARR.Domain.Common.Roles;

namespace PARR.API.Controllers.V1.Statistics
{
    /// <summary>
    /// Статистика шаблонов по типам статусов ПАРР
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class StatStatusTypeTemplates : BaseApiController
    {
        private readonly ITemplateRepository templateService;
        private readonly ITemplateStatusTypeRepository templateStatusTypeService;
        private readonly IMapper mapper;

        public StatStatusTypeTemplates(
            ITemplateRepository templateService,
            ITemplateStatusTypeRepository templateStatusTypeService,
            IMapper mapper
            )
        {
            this.templateService = templateService;
            this.templateStatusTypeService = templateStatusTypeService;
            this.mapper = mapper;
        }


        /// <summary>
        /// Статистика шаблонов по StatusType
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatStatusTypeTemplates.Get)]
        public async Task<IActionResult> Get()
        {
            var templateStatistics = await templateService.Get()
                                                .AsNoTracking()
                                                .GroupBy(t => t.StatusTypeId)
                                                .Select(t => new
                                                {
                                                    StatusTypeId = t.Key,
                                                    TempaltesCount = t.Count()
                                                })
                                                .ToDictionaryAsync(t => t.StatusTypeId, t => t.TempaltesCount);

            var statusTypes = await templateStatusTypeService.Get()
                                        .AsNoTracking()
                                        .OrderBy(t => t.Id)
                                        .ToListAsync();

            var response = statusTypes.Select(t => new StatStatusTypeTemplatesResponse
            {
                StatusType = mapper.Map<TemplateStatusTypeResponse>(t),
                TemplateCount = templateStatistics.TryGetValue(t.Id, out int count) ? count : 0
            }).ToList();


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

    }
}
