using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests.BaseRequests;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Contracts.V1.Responses.Statistics;
using PARR.API.Controllers.V1.Base;
using PARR.API.Helpers;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.NextRunServices;
using PARR.Domain.Common.Roles;

namespace PARR.API.Controllers.V1.Statistics
{
    /// <summary>
    /// Статистика по юнитам (ЭК)
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class StatUnitController : BaseApiController
    {
        private readonly IUnitRepository unitService;
        private readonly INextRunService nextRunService;

        public StatUnitController(
            IUnitRepository unitService,
            INextRunService nextRunService
            )
        {
            this.unitService = unitService;
            this.nextRunService = nextRunService;
        }

        /// <summary>
        /// Статистика синхронизации юнитов (ЭК) с АИХИТ за сегодня
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatUnit.Get)]
        public async Task<IActionResult> Get([FromQuery] TimeZoneOffsetClient timeZoneQuery)
        {
            var todayStartUtc = TimeZoneDateHelper.GetUtcSartOfDay(
                    DateOnly.FromDateTime(DateTimeOffset.UtcNow.ToOffset(timeZoneQuery.TimeZoneOffset).DateTime),
                    timeZoneQuery.TimeZoneOffset
                );

            var response = new StatUnitResponse
            {
                AllHosts = await unitService.Get().AsNoTracking().CountAsync(),
                CreatedLastDay = await unitService.Get().AsNoTracking().CountAsync(t => t.DateCreated.UtcDateTime >= todayStartUtc),
                UpdatedLastDay = await unitService.Get()
                                            .Where(t => t.UnitValues.Any(v => v.DateModified.HasValue && v.DateModified.Value.UtcDateTime >= todayStartUtc))
                                            .AsNoTracking()
                                            .CountAsync()
            };

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


        /// <summary>
        /// Получить статистику созданных юнитов (ЭК) за период
        /// </summary>
        /// <param name="timeZoneQuery"></param>
        /// <param name="startPeriodDays"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatUnit.GetForPeriod)]
        public async Task<IActionResult> GetForPeriod([FromQuery] TimeZoneOffsetClient timeZoneQuery, [FromQuery] int startPeriodDays = 3)
        {
            // Формируем период
            var userEnd = DateOnly.FromDateTime(DateTimeOffset.UtcNow.ToOffset(timeZoneQuery.TimeZoneOffset).DateTime);
            var userStart = userEnd.AddDays(-startPeriodDays);

            var (utcStart, utcEnd) = TimeZoneDateHelper.GetUtcDateRange(
                                                            userStart,
                                                            userEnd.AddDays(1),
                                                            timeZoneQuery.TimeZoneOffset);

            var allRecords = await unitService.Get()
                                   .AsNoTracking()
                                   .FilterByDateRangeUtc(t => t.DateCreated, utcStart, utcEnd)
                                   .Select(t => new { t.Id, t.DateCreated })
                                    .ToListAsync();


            var resultDict = allRecords.GroupByUserDate(t => t.DateCreated, timeZoneQuery.TimeZoneOffset);

            var daysList = await nextRunService.GetWorkDaysAsync(userStart, userEnd, false);

            var response = daysList.Select(date => new StatUnitPeriodResponse
            {
                Date = date,
                CreatedUnitsCount = resultDict.TryGetValue(date, out var cnt) ? cnt : 0
            }).OrderBy(t => t.Date).ToList();

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


        /// <summary>
        /// Количество юнитов (ЭК) в шаблонах
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatUnit.GetWithTemplates)]
        public async Task<IActionResult> GetWithTemplates()
        {
            //считаем именно хосты в шаблонах, т е один хост может быть в нескольких шаблонах

            var response = new StatUnitTemplateResponse
            {
                AllUnits = await unitService.Get().CountAsync(),
                UnitsInTemplates = await unitService.Get().Include(t => t.Templates).CountAsync(t => t.Templates.Any())
            };

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