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

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 IUnitFieldValueService unitFieldValueService;
        private readonly ICalendarService calendarService;

        public StatUnitFieldValuesController(
            IApplicationService applicationService,
            IUnitFieldValueService unitFieldValueService,
            ICalendarService calendarService
            )
        {
            this.applicationService = applicationService;
            this.unitFieldValueService = unitFieldValueService;
            this.calendarService = calendarService;
        }

        /// <summary>
        /// Статистика синхронизации полей юнитов (ЭК) с АИХИТ за последние сутки
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatUnitFieldValues.Get)]
        public async Task<IActionResult> Get()
        {
            var queryDate = DateTimeOffset.UtcNow.AddDays(-1);

            var response = new StatUnitFieldValuesResponse
            {
                AllValues = await unitFieldValueService.Get().CountAsync(),
                CreatedLastDay = await unitFieldValueService.Get().CountAsync(t => t.DateCreated >= queryDate),
                //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 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 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();

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



    }
}
