using AutoMapper;
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;
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;

namespace PARR.API.Controllers.V1.Statistics
{
    /// <summary>
    /// Статистика по нарядам
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class StatOrderController : BaseApiController
    {
        private readonly IOrderService orderService;
        private readonly IOrderStatusService orderStatusService;
        private readonly IMapper mapper;
        private readonly ICalendarService calendarService;

        public StatOrderController(
            IOrderService orderService,
            IOrderStatusService orderStatusService,
            IMapper mapper,
            ICalendarService calendarService
            )
        {
            this.orderService = orderService;
            this.orderStatusService = orderStatusService;
            this.mapper = mapper;
            this.calendarService = calendarService;
        }

        /// <summary>
        /// Статистика по нарядам - всего в ПАРР / загружено за последние сутки
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatOrder.Get)]
        public async Task<IActionResult> Get()
        {
            var queryDate = DateTimeOffset.UtcNow.AddDays(-1);

            var response = new StatOrderResponse
            {
                AllCount = await orderService.Get().CountAsync(),
                DownloadedLastDayCount = await orderService.Get().CountAsync(t => t.DateCreated >= queryDate)
            };

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


        /// <summary>
        /// Статистика по нарядам - кол-во заданий на изменение нарядов в ЕСПП
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatOrder.TaskToEspp)]
        public async Task<IActionResult> TaskToEspp()
        {
            var response = new StatTaskToEsppResponse
            {
                AllCount = await orderService.Get().CountAsync(),
                // такая же логика в PARR.Master
                TaskCount = await orderService.Get().CountAsync(t => t.NextStatusCode.HasValue && t.NextStatusCode.Value != t.StatusCode)
            };

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


        /// <summary>
        /// Статистика по нарядам - по статусам в ПАРР
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatOrder.Statuses)]
        public async Task<IActionResult> Statuses()
        {
            var statuses = await orderStatusService.Get().OrderBy(t => t.Code).ToListAsync();


            var response = new List<StatOrderStatusesResponse>();
            foreach (var stat in statuses)
            {
                response.Add(new StatOrderStatusesResponse
                {
                    Status = mapper.Map<OrderStatusResponse>(stat),
                    Count = await orderService.Get().CountAsync(t => t.StatusCode == stat.Code)
                });
            }

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


        /// <summary>
        /// Статистика по нарядам - по статусу за последние сутки
        /// </summary>
        /// <param name="statusCode">1,2,3,4,5</param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatOrder.GetStatusesLastDay)]
        public async Task<IActionResult> GetStatusesLastDay([FromRoute] int statusCode)
        {
            var status = await orderStatusService.Get().FirstOrDefaultAsync(t => t.Code == statusCode);

            if (status == null)
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найден статус с кодом: {statusCode}" } }));

            var queryDate = DateTimeOffset.UtcNow.AddDays(-1);

            var response = new StatGetStatusesLastDayResponse
            {
                Count = await orderService.Get().CountAsync(t => t.DateModified >= queryDate && t.StatusCode == statusCode),
                Status = mapper.Map<OrderStatusResponse>(status)
            };

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


        /// <summary>
        /// Получить статистику добавления новых нарядов за период
        /// </summary>
        /// <param name="timeZoneQuery"></param>
        /// <param name="startPeriodDays"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatOrder.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 = orderService.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,
                                OrderCount = t.Count()
                            });

            var result = await query.ToListAsync();

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

            var response = new List<StatOrderGetForPeriodResponse>();

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

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

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


    }
}
