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.Unit;

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

        public StatUnitController(
            IUnitService unitService,
            ICalendarService calendarService
            )
        {
            this.unitService = unitService;
            this.calendarService = calendarService;
        }

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

            var response = new StatUnitResponse
            {
                AllHosts = await unitService.Get().CountAsync(),
                CreatedLastDay = await unitService.Get().CountAsync(t => t.DateCreated >= queryDate),
                //UpdatedLastDay = await hostService.Get().CountAsync(t => t.DateModified.HasValue && t.DateModified.Value >= queryDate)
                UpdatedLastDay = await unitService.Get()
                                            .Include(t => t.UnitValues)
                                            .Where(t => t.UnitValues.Any(v => v.DateModified.HasValue && v.DateModified.Value >= queryDate))
                                            .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 endPeriod = calendarService.GetDateWithTimeZoneOffset(DateTimeOffset.UtcNow, timeZoneQuery.TimeZoneOffsetHours);
            var startPeriod = endPeriod.AddDays(-startPeriodDays);

            var query = unitService.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,
                    UnitCount = t.Count()
                });

            var result = await query.ToListAsync();

            var daysList = calendarService.GetDatesForPeriod(startPeriod, endPeriod);

            var response = new List<StatUnitPeriodResponse>();

            daysList.ForEach(date =>
            {
                response.Add(new StatUnitPeriodResponse
                {
                    Date = date,
                    CreatedUnitsCount = result.FirstOrDefault(t => DateOnly.FromDateTime(t.Date) == date)?.UnitCount ?? 0
                });
            });

            response = response.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));
        }
    }
}
