using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Extensions;
using PARR.API.Services.Interfaces;
using PARR.DAL.Cache.Services.Base;
using PARR.DAL.Contracts;
using PARR.DAL.DomainModels;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.Models.Job;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.Services.Interfaces.Unit;
using PARR.DAL.TransformServices;

namespace PARR.API.Controllers.V1
{
    [Authorize]
    public class TestController : BaseApiController
    {
        private readonly IClientService clientService;
        private readonly IEsppScheduleTransformService esppScheduleTransformService;
        private readonly IRedisCacheService redisCacheService;
        private readonly IWeekendDayService weekendDayService;
        private readonly IUnitService unitService;
        private readonly IFieldFilterService fieldFilterService;
        private readonly IJobService jobService;
        private readonly IJobUnitFilterService jobUnitFilterService;
        private readonly IUnitFilterService unitFilterService;
        private readonly IMapper mapper;

        public TestController(
            IClientService clientService,
            IEsppScheduleTransformService esppScheduleTransformService,
            IRedisCacheService redisCacheService,
            IWeekendDayService weekendDayService,
            IUnitService unitService,
            IFieldFilterService fieldFilterService,
            IJobService jobService,
            IJobUnitFilterService jobUnitFilterService,
            IUnitFilterService unitFilterService,
            IMapper mapper
            )
        {
            this.clientService = clientService;
            this.esppScheduleTransformService = esppScheduleTransformService;
            this.redisCacheService = redisCacheService;
            this.weekendDayService = weekendDayService;
            this.unitService = unitService;
            this.fieldFilterService = fieldFilterService;
            this.jobService = jobService;
            this.jobUnitFilterService = jobUnitFilterService;
            this.unitFilterService = unitFilterService;
            this.mapper = mapper;
        }


        /// <summary>
        /// Получить мой ip
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Test.GetMyIp)]
        public IActionResult GetMyIp()
        {
            var ipAddress = clientService.GetClientIp();

            var ip = ipAddress?.ToString();

            return Ok(new Response<object>(new { ip }, true));
        }


        /// <summary>
        /// Получить следующую дату запуска
        /// </summary>
        /// <param name="applicationInWorkId"></param>
        /// <param name="lastRunDate"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Test.GetNextScheduleDate)]
        public async Task<IActionResult> GetNextScheduleDate([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
        {
            var result = await esppScheduleTransformService.GetNextDateAsync(applicationInWorkId, lastRunDate);
            return Ok(result);
        }


        /// <summary>
        /// Получить следующее расписание
        /// </summary>
        /// <param name="applicationInWorkId"></param>
        /// <param name="lastRunDate"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Test.GetNextSchedule)]
        public async Task<IActionResult> GetNextSchedule([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
        {
            var result = await esppScheduleTransformService.GetNextScheduleAsync(applicationInWorkId, lastRunDate);
            return Ok(result);
        }


        /// <summary>
        /// Записать в кэш и получить обратно значение из кэша
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost(ApiRoutes.Test.CreateCache)]
        public async Task<IActionResult> CreateCache([FromBody] CaheRequestTest request)
        {
            await redisCacheService.SetCachedDataAsync(request.Key, request, TimeSpan.FromMinutes(1));

            var fromCache = await redisCacheService.GetCachedDataAsync<CaheRequestTest>(request.Key);

            return Ok(new { fromCache });
        }


        /// <summary>
        /// Проверка, это рабочий день?
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Test.IsWorkDay)]
        public async Task<IActionResult> IsWorkDay([FromQuery] DateOnly date)
        {
            return Ok(await weekendDayService.IsWorkDayAsync(date, true));
        }


        /// <summary>
        /// Тестовый метод
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Test.TestHandler)]
        public async Task<IActionResult> Test()
        {
            //var job = new Job
            //{
            //    Id = Guid.NewGuid(),
            //    Name = "ВИ-VMWARE ТО-1 Мониторинг и анализ работы виртуальной инфраструктуры",
            //    DateCreated = DateTimeOffset.Now,
            //    TemplateNameMask = "ЭИТИ_%РГ%_%ТНК%_%ЭК%",
            //    TnkId = Guid.Parse("9b7e0251-cb13-427c-ac71-16baa2a111dd")
            //};

            //var jobDetails = new JobDetails {
            //    Id = Guid.NewGuid(),
            //    UnitFilter = "ВРТ-VMWARE-*",
            //    JobId = job.Id,
            //    ShortDescription = "Мониторинг и анализ работы виртуальной инфраструктуры",
            //    FullDescription = "Проверка журналов (лог-файла) событий (warning, alarm) объектов виртуальной инфраструктуры (ВМ, хост, кластер, датацентр, virtual center и др.)",
            //    Solution = "Работы проведены",
            //    Duration = "7 00:00:00",
            //    ReferenceDate = new DateTimeOffset(2026,01,01,00,00,00,new TimeSpan(0))
            //};

            //var fieldFilter = new FieldFilter
            //{
            //    Id = Guid.NewGuid(),
            //    JobDetailsId = jobDetails.Id,
            //    FieldId = Guid.Parse("08b42860-09a7-4a1f-aa4f-0290e86df884"),
            //    ValueMask = "виртуальный комплекс"
            //};
            ////await jobService.CreateAsync(job);
            ////await jobService.CommitAsync();
            //if (await jobService.CreateAsync(job))
            //    if (await jobDetailsService.CreateAsync(jobDetails))
            //        if (await fieldFilterService.CreateAsync(fieldFilter))
            //            await jobService.CommitAsync(); 
            //var unit = await unitService.Get().Include(t => t.Parents).Include(t => t.Childs).FirstOrDefaultAsync(t => t.Id == Guid.Parse("01fda0bd-3423-4b12-965b-2947153d1d87"));

            //var parent = unit?.Parents;
            //var child = unit?.Childs;

            return Ok();
        }


        //[HttpGet(ApiRoutes.Test.GetWorkDay)]
        //public async Task<IActionResult> GetWorkDay([FromRoute] DateTimeOffset date)
        //{
        //    var result = await esppScheduleTransformService.GetWorkDayAsync(date);

        //    return Ok(result);
        //}
    }

    public class CaheRequestTest
    {
        public required string Key { get; set; }

        public required string Value { get; set; }
    }
}
