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

namespace PARR.API.Controllers.V1.Statistics
{
    /// <summary>
    /// Статистика по значениям unit.FieldValues полученных из АИХИТ
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class StatUnitFieldValuesController : BaseApiController
    {
        //private readonly IApplicationService applicationService;
        private readonly IUnitFieldValueRepository unitFieldValueService;
        private readonly INextRunService nextRunService;

        //private readonly ICalendarService calendarService;

        public StatUnitFieldValuesController(
            //IApplicationService applicationService,
            IUnitFieldValueRepository unitFieldValueService,
            //ICalendarService calendarService
            INextRunService nextRunService
            )
        {
            //this.applicationService = applicationService;
            this.unitFieldValueService = unitFieldValueService;
            this.nextRunService = nextRunService;
            //this.calendarService = calendarService;
        }

        /// <summary>
        /// Статистика синхронизации полей юнитов (ЭК) с АИХИТ за сегодня
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatUnitFieldValues.Get)]
        public async Task<IActionResult> Get([FromQuery] TimeZoneOffsetClient timeZoneQuery)
        {
            // Формируем начало "сегодня" в часовом поясе пользователя
            var userNow = DateTimeOffset.UtcNow.ToOffset(timeZoneQuery.TimeZoneOffset);
            var userTodayStart = new DateTimeOffset(
                                            userNow.Year, userNow.Month, userNow.Day,
                                            0, 0, 0,
                                            timeZoneQuery.TimeZoneOffset);

            // Конвертируем в UTC для запроса к БД
            var todayStartUtc = userTodayStart.UtcDateTime;

            var response = new StatUnitFieldValuesResponse
            {
                AllValues = await unitFieldValueService.Get().AsNoTracking().CountAsync(),
                CreatedLastDay = await unitFieldValueService.Get().AsNoTracking().CountAsync(t => t.DateCreated.UtcDateTime >= todayStartUtc),
                //UpdatedLastDay = await applicationService.Get().CountAsync(t => t.DateModified.HasValue && t.DateModified.Value >= queryDate),
            };

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


        /// <summary>
        /// Получить статистику за период
        /// </summary>
        /// <param name="timeZoneQuery"></param>
        /// <param name="startPeriodDays"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatUnitFieldValues.GetForPeriod)]
        public async Task<IActionResult> GetForPeriod([FromQuery] TimeZoneOffsetClient timeZoneQuery, [FromQuery] int startPeriodDays = 3)
        {
            var userEndPeriod = DateTimeOffset.UtcNow.Add(timeZoneQuery.TimeZoneOffset);
            var userStartPeriod = userEndPeriod.AddDays(-startPeriodDays);

            var utcEndPeriod = userEndPeriod.UtcDateTime;
            var utcStartPeriod = userStartPeriod.UtcDateTime;

            var allRecords = await unitFieldValueService.Get()
                            .AsNoTracking()
                            .Where(t =>
                                //t.DateCreated.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date >= startPeriod.Date
                                //&& t.DateCreated.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date <= endPeriod.Date
                                utcStartPeriod <= t.DateCreated.UtcDateTime && t.DateCreated.UtcDateTime < utcEndPeriod
                            ).Select(t => new { t.Id, t.DateCreated })
                            .ToListAsync();

            var resultDict = allRecords.GroupBy(t => DateOnly.FromDateTime(t.DateCreated.ToOffset(timeZoneQuery.TimeZoneOffset).DateTime))
                                   .ToDictionary(t => t.Key, t => t.Count());

            //var endPeriod = calendarService.GetDateWithTimeZoneOffset(DateTimeOffset.UtcNow, timeZoneQuery.TimeZoneOffsetHours);
            //var startPeriod = endPeriod.AddDays(-startPeriodDays);

            //var query = unitFieldValueService.Get()
            //                .Where(t =>
            //                    t.DateCreated.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date >= startPeriod.Date
            //                    && t.DateCreated.DateTime.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date <= endPeriod.Date
            //                )
            //                .GroupBy(t => t.DateCreated.AddHours(timeZoneQuery.TimeZoneOffsetHours).Date)
            //                .Select(t => new
            //                {
            //                    Date = t.Key,
            //                    Count = t.Count()
            //                });

            //var result = await query.ToListAsync();

            //var daysList = calendarService.GetDatesForPeriod(startPeriod, endPeriod);
            var daysList = await nextRunService.GetWorkDaysAsync(DateOnly.FromDateTime(userStartPeriod.DateTime), DateOnly.FromDateTime(userEndPeriod.DateTime), false);

            //var response = new List<StatApplicationPeriodResponse>();

            //daysList.ForEach(date =>
            //{
            //    response.Add(new StatApplicationPeriodResponse
            //    {
            //        Date = date,
            //        CreatedApplicationsCount = result.FirstOrDefault(t => DateOnly.FromDateTime(t.Date) == date)?.Count ?? 0
            //    });
            //});

            //response = response.OrderBy(t => t.Date).ToList();

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

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



    }
}
