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;
using PARR.Core.Services.NextRunServices;
using PARR.Domain.Common.Roles;
using PARR.Domain.Enums;

namespace PARR.API.Controllers.V1.Statistics
{
    /// <summary>
    /// Статистика по шаблонам
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class StatTemplateController : BaseApiController
    {
        private readonly ITemplateRepository templateService;
        private readonly INextRunService nextRunService;

        public StatTemplateController(
            ITemplateRepository templateService,
            INextRunService nextRunService
            )
        {
            this.templateService = templateService;
            this.nextRunService = nextRunService;
        }

        /// <summary>
        /// Статистика по шаблонам
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatTemplate.Get)]
        public async Task<IActionResult> Get()
        {
            var response = new StatTemplateResponse
            {
                ActivateScheduleCount = await templateService.Get().AsNoTracking().CountAsync(t => t.IsActiveSchedule),
                ActivateTemplateCount = await templateService.Get().AsNoTracking().CountAsync(t => t.IsActiveTemplate),
                TemplateAgentCount = await templateService.Get().AsNoTracking().CountAsync(t => t.Job!.Group!.IsAgent),
                TemplateCount = await templateService.Get().AsNoTracking().CountAsync(),
                SyncEsppScheduleCount = await templateService.Get().AsNoTracking().CountAsync(t => t.RobotConfigurations.Any(c => c.RobotCode == (int)RobotsEnum.ScheduleOrder && c.TaskStatusCode == (int)TaskStatusEnum.Ok)),
                SyncEsppTemplatesCount = await templateService.Get().AsNoTracking().CountAsync(t => t.RobotConfigurations.Any(c => c.RobotCode == (int)RobotsEnum.TemplateOrder && c.TaskStatusCode == (int)TaskStatusEnum.Ok))
            };

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


        /// <summary>
        /// Получить статистику созданных шаблонов (расписаний) в БД ПАРР
        /// </summary>
        /// <param name="timeZoneQuery"></param>
        /// <param name="startPeriodDays"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatTemplate.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 templateService.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 StatTemplatePeriodResponse
            {
                Date = date,
                CreatedTemplatesCount = resultDict.TryGetValue(date, out var cnt) ? cnt : 0
            }).OrderBy(t => t.Date).ToList();

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


    }
}
