using AutoMapper;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Schedule;
using PARR.Domain.DTOs.RobotTask;
using PARR.Domain.Entities;

namespace PARR.Core.Infrastructure.Mapping.RobotTask.Resolvers
{
    public class RobotTaskScheduleSchResolver : IValueResolver<RobotConfiguration, RobotTaskSchedule, List<RobotTaskScheduleSch>?>
    {
        private readonly IEsppSchTypeConfigRepository esppConfigRepository;
        private readonly ILogger<RobotTaskScheduleSchResolver> logger;

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

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

            var schedule = esppConfigRepository.GetEsppScheduleDto(jobGroupId);

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

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

            return response;
        }
    }
}
