using PARR.Core.Repositories.Interfaces;
using PARR.Core.Services.NextRunServices;
using PARR.Core.Services.NextRunServices.Models;
using PARR.Core.Services.Shortcodes;

namespace PARR.Test.NextRun
{
    internal class NextRunTest
    {
        //private readonly ITemplateDistributor templateDistributor;
        //private readonly INextRunService nextRunService;
        private readonly ITemplateRepository templateService;
        private readonly IShortcodesService shortcodesService;
        //private readonly ITemplateDistributorV2 templateDistributorV2;
        private readonly INextRunService nextRunServiceV2;

        public NextRunTest(
            /*ITemplateDistributor templateDistributor, */
            //INextRunService nextRunService,
            ITemplateRepository templateService,
            IShortcodesService shortcodesService,
            //ITemplateDistributorV2 templateDistributorV2,
            INextRunService nextRunServiceV2
            )
        {
            //this.templateDistributor = templateDistributor;
            //this.nextRunService = nextRunService;
            this.templateService = templateService;
            this.shortcodesService = shortcodesService;
            //this.templateDistributorV2 = templateDistributorV2;
            this.nextRunServiceV2 = nextRunServiceV2;
        }



        public async Task Test()
        {
            //var nextRun = await nextRunServiceV2.GetNextRunForTemplateAsync(Guid.Parse("0bef9892-1672-40b7-a2bd-528f9bd1ef22"), false);



            #region тестирование INextRunServiceV2

            //рапсределить
            //var distributeResult = await nextRunServiceV2.GetNextRunForJobGroupWithAutoDistributionAsync(Guid.Parse("d25d8a9e-898f-417a-9bec-ef3a356e7c94"), TemplateStatusTypeEnum.Used);

            // новый шаблон - автодистриб
            //var nextRunForNewTemplateDistrib = await nextRunServiceV2.GetNextRunForNewTemplateAsync(Guid.Parse("d25d8a9e-898f-417a-9bec-ef3a356e7c94"), workGroupName: "ЦКИТ-ВСИБ", responseAreaName: "92-ВСИБ");

            // новый шаблон - еспп
            //var nextRunForNewTemplateEspp = await nextRunServiceV2.GetNextRunForNewTemplateAsync(Guid.Parse("692531d6-4ef4-4a6d-99be-d2ef375d520f"), workGroupName: "ЦКИТ-ЗСИБ", responseAreaName: "83-ЗСИБ");

            // существующий шаблон - автодистриб
            //var nextRunForExistTemplateDistib = await nextRunServiceV2.GetNextRunForTemplateAsync(Guid.Parse("05769f8d-9630-4683-b07a-070d69e1dc12"), false);

            // существующий шаблон - еспп
            //var nextRunForExistTemplateEspp = await nextRunServiceV2.GetNextRunForTemplateAsync(Guid.Parse("1329dfca-5e09-4b19-a2e6-560a4896080c"), false);

            #endregion


            #region Тестирование templateDistributorV2

            //var duration = 2;
            //var offset = TimeSpan.FromHours(3);

            //var startDate = new DateOnly(2026, 2, 10);
            //var referenceDate = new DateTimeOffset(2026, 2, 13, 23, 0, 0, TimeSpan.Zero);

            //var templates = GetTemplates();
            //var templatesEmpty = new List<TemplateNextRunDto>();
            //var templatesToHandeler = templatesEmpty; // templatesEmpty // templates

            //// распределить шаблоны
            //var distributedTemplates = await templateDistributorV2.DistributeTemplatesAsync(startDate, duration, referenceDate, offset, templates, true);

            //// получить актуальный nextRun
            //var targetTemplate = new TemplateNextRunDto(Guid.Parse("DA151719-2742-4260-BFFE-012B61591053"), new DateTimeOffset(2026, 2, 15, 23, 30, 0, TimeSpan.Zero));
            ////var validNextRun = await templateDistributorV2.GetNextRunForTemplateAsync(startDate, duration, referenceDate, offset, targetTemplate, templatesToHandeler, true, isNew: false);

            #endregion

            //var template = await templateService.Get().Include(t => t.Job).ThenInclude(t => t.Group).FirstAsync(t => t.Name == "ЭИТИ-ПАРР_ЦКИТ-ГВЦ_СХД ТО-1_СХД-AERODISK-432-2-4-U26-EN4SAG022-ГВЦ");
            //var responseAreae = await shortcodesService.ApplyShortcodesAsync(template.Job.ResponseAreaMask, template);
            //var nextRunWithTimezone = nextRunService.GetNextRunWithTimezoneEsppAndResponseArea(template.NextRun, template.Job?.Group?.IsResponseAreaTimezone, responseAreae);

            //DateTimeOffset dbNextRun = new DateTimeOffset(2026, 2, 2, 4, 0, 0, TimeSpan.Zero);
            //var result = nextRunService.GetNextRunWithTimezoneEsppAndResponseArea(dbNextRun, true, "96-ДВС");

            //var template = await templateService.Get()
            //                            .AsNoTracking()
            //                            .FirstAsync(t => t.Name == "ЭИТИ-ПАРР_ЦКИТ-ДВС_ТО-1 ОСМОТР ОБОРУД. (15-29 СТОЕК)_СРВ-МАШЗАЛ-315-01-ДВС");

            //var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);

            //var esppResult = nextRunService.GetNextRunWithTimezoneEsppAndResponseArea(newNextRun, true, "96-ДВС");




            // GetWorkDaysTESTAsync
            //var aaa = await templateDistributor.GetWorkDaysTESTAsync(GetDateStart(), GetDateStart().AddDays(periodDays), true, referenceDate);

            //await DistributeTemplatesAsync();
            //await GetValidNextRunForTemplateAsync();

            // распределить шаблоны (не сохраняя в БД)
            //var result = await nextRunService.GetNextRunForJobGroupWithAutoDistributionAsync(Guid.Parse("eadc5498-dba6-4f10-9b4b-a1653e3c3e61"));

            // получить nextRun для еще не созданного шаблона
            //var nextRunForNullTemplate = await nextRunService.GetNextRunForNewTemplateAsync(Guid.Parse("eadc5498-dba6-4f10-9b4b-a1653e3c3e61"));

            // получить nextRun для существующего шаблона
            // var nextRunForExistTemplate = await nextRunService.GetNextRunForTemplateAsync(Guid.Parse("20fc3581-984e-4c9a-8b46-8a55c3401725"), false);

        }

        /// <summary>
        /// Получить актуальный NextRun
        /// </summary>
        /// <returns></returns>
        private async Task GetValidNextRunForTemplateAsync()
        {
            // исключать выходные и праздники
            var excludeWeekends = true;
            bool isNew = false;

            var targetTemplate = new TemplateNextRunDto
            (
                Id: Guid.Parse("11F047E6-3631-4676-8959-FC75FF6BC963"),
                //NextRun = new DateTimeOffset(2026, 1, 20, 4, 0, 0, TimeSpan.Zero)
                NextRun: null
            );

            //var template = await templateDistributor.GetValidNextRunForTemplateAsync(GetDateStart(), periodDays, referenceDate, targetTemplate, new List<TemplateNextRunDto>(), excludeWeekends, isNew);
        }


        /// <summary>
        /// распределить шаблоны
        /// </summary>
        private async Task DistributeTemplatesAsync()
        {
            // исключать выходные и праздники
            var excludeWeekends = true;

            // var templates = await templateDistributor.DistributeTemplatesAsync(GetDateStart(), periodDays, referenceDate, GetTemplates(), excludeWeekends);

            //await GetValidNextRunForTemplateAsync(templates);
        }


        /// <summary>
        /// получить nextRun
        /// </summary>
        private async Task GetValidNextRunForTemplateAsync(List<TemplateNextRunDto>? templates = null)
        {
            //var templateList = templates ?? GetTemplates();

            //var targetTemplate = new TemplateNextRunDto { Id= Guid.Parse("4C2F61E9-7B47-4049-A881-9200D71303F7"), NextRun= new DateTimeOffset(2025, 12, 1, 3, 0, 0, TimeSpan.Zero) };

            //var distribTemplates = await templateDistributor.GetValidNextRunForTemplateAsync(GetDateStart(), GetDateEnd(), referenceDate, targetTemplate, templateList);

            //// еще раз
            //templateList.Add(targetTemplate);
            //var targetTemplate2 = new TemplateNextRunDto { Id = Guid.Parse("4C2F61E9-7B47-4049-A881-9200D71303F7"), NextRun = new DateTimeOffset(2025, 12, 1, 3, 0, 0, TimeSpan.Zero) };
            //var distribTemplates2 = await templateDistributor.GetValidNextRunForTemplateAsync(GetDateStart(), GetDateEnd(), referenceDate, targetTemplate2, templateList);

        }


        //private DateOnly GetDateStart()
        //{
        //    var today = DateOnly.FromDateTime(DateTime.UtcNow.Date);

        //    var refDate = DateOnly.FromDateTime(referenceDate.Date);

        //    return today < refDate ? refDate : today;
        //}

        //private DateOnly GetDateEnd()
        //{
        //    return GetDateStart().AddDays(periodDays);
        //}


        private List<TemplateNextRunDto> GetTemplates()
        {
            var templates = new List<TemplateNextRunDto>();

            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("55F047E6-3631-4676-8959-FC75FF6BC963"), NextRun: new DateTimeOffset(2027, 1, 15, 3, 0, 0, TimeSpan.Zero)));
            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("DD15E9F6-AAD4-4FE6-9441-7E7FF67781A3"), NextRun: new DateTimeOffset(2025, 12, 24, 3, 0, 0, TimeSpan.Zero)));

            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("78EE4A94-DBEE-41D1-B51A-CE3BD5AEE4D4"), NextRun: new DateTimeOffset(2025, 12, 29, 3, 0, 0, TimeSpan.Zero)));
            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("B397F1FE-DF2B-4B50-B8D6-2DABECD3D5A1"), NextRun: new DateTimeOffset(2025, 12, 18, 3, 0, 0, TimeSpan.Zero)));
            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("619D9621-2B45-4108-AF54-CF96862A8E9B"), NextRun: new DateTimeOffset(2025, 12, 18, 3, 0, 0, TimeSpan.Zero)));
            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("D74D831C-D435-46BF-9B5F-A24884AAA7DC"), NextRun: new DateTimeOffset(2025, 12, 25, 3, 0, 0, TimeSpan.Zero)));
            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("DE7241F1-5C62-4164-A3DC-99B946350E10"), NextRun: new DateTimeOffset(2026, 2, 16, 23, 30, 0, TimeSpan.Zero)));
            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("94A7375E-D1BD-49B7-9186-D26E85F1CF74"), NextRun: new DateTimeOffset(2025, 12, 18, 3, 0, 0, TimeSpan.Zero)));
            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("B3681F5F-10A5-425C-BBEA-EA2B85FE0967"), NextRun: new DateTimeOffset(2025, 12, 18, 3, 0, 0, TimeSpan.Zero)));
            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("3259B408-48A3-4995-AF9A-097477ECAB81"), NextRun: new DateTimeOffset(2025, 12, 18, 3, 0, 0, TimeSpan.Zero)));
            templates.Add(new TemplateNextRunDto(Id: Guid.Parse("25F53A28-D657-4B9A-82F3-CE9AF4D53385"), NextRun: new DateTimeOffset(2025, 12, 30, 3, 0, 0, TimeSpan.Zero)));
            //templates.Add(new TemplateNextRunDto { Id = Guid.Parse("F75F6B1A-875F-4CB2-98C8-6721FD06C18C"), NextRun = new DateTimeOffset(2025, 12, 18, 3, 0, 0, TimeSpan.Zero) });
            //templates.Add(new TemplateNextRunDto { Id = Guid.Parse("2C06C63D-BE92-4312-98FB-0547E74B8A33"), NextRun = new DateTimeOffset(2025, 12, 18, 3, 0, 0, TimeSpan.Zero) });
            //templates.Add(new TemplateNextRunDto { Id = Guid.Parse("B22D314E-9F86-49BB-826F-20919EC55A7F"), NextRun = new DateTimeOffset(2025, 12, 18, 3, 0, 0, TimeSpan.Zero) });
            //templates.Add(new TemplateNextRunDto { Id = Guid.Parse("061CB58A-B350-456F-8E02-C937D488D6FC"), NextRun = null });

            //templates.Add(new TemplateNextRunDto { Id = Guid.Parse("C51E2C3F-655D-4395-BF9D-D6D64DA314D9"), NextRun = null });
            //templates.Add(new TemplateNextRunDto { Id = Guid.Parse("C9A77DEF-0FB8-4903-87B7-16B8C3EC97A4"), NextRun = null });
            //templates.Add(new TemplateNextRunDto { Id = Guid.Parse("EC703575-B38F-4A7F-9010-BBB3F92EDEA9"), NextRun = null });
            //templates.Add(new TemplateNextRunDto { Id = Guid.Parse("188181C3-AACD-4205-BCB6-7414966CB33B"), NextRun = null });


            return templates;
        }

    }
}
