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

namespace PARR.API.Controllers.V1.Statistics
{
    /// <summary>
    /// Статистика распределения шаблонов
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class StatTemplateDistributionController : BaseApiController
    {
        private readonly ITemplateService templateService;
        private readonly IWorkGroupService workGroupService;
        private readonly IMapper mapper;

        public StatTemplateDistributionController(
            ITemplateService templateService,
            IWorkGroupService workGroupService,
            IMapper mapper
            )
        {
            this.templateService = templateService;
            this.workGroupService = workGroupService;
            this.mapper = mapper;
        }


        /// <summary>
        /// Статистика распределения шаблонов по JobId (ApplicationInWorkId)
        /// </summary>
        /// <param name="JobId"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatTemplateDistribution.Get)]
        public async Task<IActionResult> Get([FromRoute] Guid jobId)
        {
            // f87dbe9f-cabf-4108-9c93-12068d4b48a5

            var query = templateService.Get()
                                .Include(t => t.Unit)
                                .Where(t => t.JobId == jobId)
                                .GroupBy(t => t.Unit!.BaseFields!.WorkGroup)
                                .Select(x => new
                                {
                                    WorkGroup = x.Key,
                                    CountTemplates = x.Count(),
                                    IsActivatedAllCount = x.Count(t => t.IsActiveTemplate && t.IsActiveSchedule),
                                    IsDeactivatedAllCount = x.Count(t => !t.IsActiveTemplate || !t.IsActiveSchedule || (!t.IsActiveTemplate && !t.IsActiveSchedule)),
                                    GroupingByDate =
                                        x.GroupBy(d => d.NextRun).OrderBy(d => d.Key).Select(d =>
                                                new
                                                {
                                                    Date = d.Key,
                                                    //Всего
                                                    Count = d.Count(),
                                                    //Только активированных
                                                    IsActivatedCount = d.Count(t => t.IsActiveTemplate && t.IsActiveSchedule),
                                                    //Только деактивированных
                                                    IsDeactivatedCount = d.Count(t => !t.IsActiveTemplate || !t.IsActiveSchedule || (!t.IsActiveTemplate && !t.IsActiveSchedule))
                                                }
                                            )
                                });

            var statResult = await query.ToListAsync();

            var workGroups = await workGroupService.Get()
                                    .Include(t => t.ResponseArea)
                                    .Where(t => statResult.Select(x => x.WorkGroup).Any(w => w == t.Name))
                                    .ToListAsync();


            var response = statResult.Select(stat => new StatTemplateDistributorResponse
            {
                WorkGroup = mapper.Map<WorkGroupResponse>(workGroups.FirstOrDefault(x => x.Name == stat.WorkGroup)),//TODO Migration to job
                AllCount = stat.CountTemplates,
                IsActivatedAllCount = stat.IsActivatedAllCount,
                IsDeactivatedAllCount = stat.IsDeactivatedAllCount,
                Stat = stat.GroupingByDate.Select(x => new StatTemplateDistributorDateStat
                {
                    AllCount = x.Count,
                    Date = x.Date,
                    IsActivatedCount = x.IsActivatedCount,
                    IsDeactivatedCount = x.IsDeactivatedCount
                }).ToList()
            })
            .OrderBy(t => t.WorkGroup?.Name)
            .ToList();


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