using AutoMapper;
using PARR.API.Contracts.V1.Responses;
using PARR.Core.Repositories.Interfaces.Schedule;
using PARR.Domain.Entities;


namespace PARR.API.MappingProfiles.Resolvers
{
    public class RobotTaskScheduleSchResolver : IValueResolver<RobotConfiguration, RobotTaskScheduleResponse, List<RobotTaskScheduleSchResponse>?>
    {
        private readonly IEsppSchTypeConfigRepository esppConfigService;
        private readonly ILogger<RobotTaskScheduleSchResolver> logger;

        public RobotTaskScheduleSchResolver(
            IEsppSchTypeConfigRepository esppConfigService,
            ILogger<RobotTaskScheduleSchResolver> logger
            )
        {
            this.esppConfigService = esppConfigService;
            this.logger = logger;
        }

        public List<RobotTaskScheduleSchResponse>? Resolve(RobotConfiguration source, RobotTaskScheduleResponse destination, List<RobotTaskScheduleSchResponse>? destMember, ResolutionContext context)
        {
            var jobGroupId = source.Template!.Job!.GroupId;

            var schedule = esppConfigService.GetEsppScheduleDto(jobGroupId);

            if (schedule == null)
            {
                logger.LogError($"RobotTaskScheduleSchResolver: Не смог замапить расписание для робота, так как оно null. jobGroupId: {jobGroupId}");
                return null;
            }

            var response = schedule.Values.Select(t => new RobotTaskScheduleSchResponse
            {
                Order = t.Order,
                Type = t.Type.Name,
                TypeCode = t.Type.Id,
                Value = t.Value.Value
            }).OrderBy(t => t.Order).ToList();

            ////Если задача относится к распределенной модели исполнения за период месяц устанавливаем день равный NextRun
            ////УСТАРЕВШЕЕ
            //if (source.Template!.Job!.Group!.IsAutoDistributionEnabled && schedule.TypeSchedule.Id == (int)EsppSchTypeScheduleEnum.Monthly)
            //{
            //    var nextRunForRobot = nextRunModifierService.GetNextRunByAccountRobotTimeZone(source.Template.NextRun);

            //    //response.First().Value = source.Template.NextRun.Day.ToString();
            //    response.First().Value = nextRunForRobot.Day.ToString();
            //}

            return response;
        }
    }
}
