using AutoMapper;
using PARR.API.Contracts.V1.Responses;
using PARR.DAL.Contracts;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.TransformServices;

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

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

        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;
        }
    }
}
