using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Contracts.V1.Responses.Statistics;
using PARR.API.Controllers.V1.Base;
using PARR.Core.Common.Interfaces;
using PARR.Domain.Common.Roles;
using PARR.Domain.Settings;

namespace PARR.API.Controllers.V1.Statistics
{
    /// <summary>
    /// Статистика по авторизации
    /// </summary>
    [Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
    public class StatAuthController : BaseApiController
    {
        private readonly IInfluxDbService influxDbService;
        private readonly InfluxDbSettings influxDbSettings;

        public StatAuthController(
              IInfluxDbService influxDbService,
              InfluxDbSettings influxDbSettings
              )
        {
            this.influxDbService = influxDbService;
            this.influxDbSettings = influxDbSettings;
        }


        /// <summary>
        /// Кол-во запросов на авторизацию не из КЭШа
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.StatAuth.Get)]
        public async Task<IActionResult> Get([FromQuery] StatAuthGetQuery query)
        {
            var startAt = string.IsNullOrEmpty(query.StartAt) ? "-2h" : query.StartAt;

            var result = await influxDbService.QueryAsync(async handler =>
            {
                //var query = $"from(bucket: \"{influxDbSettings.Logons!.Bucket}\")  " +
                //                $"|> range(start: {startAt})  " +
                //                $"|> filter(fn: (r) => r._measurement == \"logon\")  " +
                //                $"|> drop(columns: [\"HostId\", \"UserId\"])  " +
                //                $"|> aggregateWindow(every: 5m, fn: count)";

                var query = $"from(bucket: \"{influxDbSettings.Logons!.Bucket}\")  " +
                                    $"|> range(start: {startAt})  " +
                                    $"|> filter(fn: (r) => r._measurement == \"logon\")  " +
                                    $"|> drop(columns: [\"UnitId\", \"UserId\"])  " +
                                    $"|> aggregateWindow(every: 5m, fn: count)";

                var tables = await handler.QueryAsync(query, influxDbSettings.Organization);

                return tables.SelectMany(table =>

                    table.Records.Select(record => new StatAuthResponse
                    {
                        Date = (DateTimeOffset)record.GetTimeInDateTime(),
                        Count = int.Parse(record.GetValue()?.ToString() ?? "0")
                    })
                );
            }, influxDbSettings.Logons!.Token);

            if (result == null)
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при получении статистики" } }));


            return Ok(new Response<List<StatAuthResponse>>(result.ToList(), true));
        }

    }
}
