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

namespace PARR.API.MappingProfiles.Resolvers
{
    public class JobGroupScheduleResolver : IValueResolver<JobGroup, JobGroupResponse, JobGroupScheduleResponse?>
    {
        private readonly IEsppSchTypeConfigService esppConfigService;
        private readonly ILogger<JobGroupScheduleResolver> logger;
        private readonly IMapper mapper;
        private readonly SettingsFromDb settingsFromDb;

        public JobGroupScheduleResolver(
            IEsppSchTypeConfigService esppConfigService,
            ILogger<JobGroupScheduleResolver> logger,
            IMapper mapper,
            SettingsFromDb settingsFromDb
            )
        {
            this.esppConfigService = esppConfigService;
            this.logger = logger;
            this.mapper = mapper;
            this.settingsFromDb = settingsFromDb;
        }


        public JobGroupScheduleResponse? Resolve(JobGroup source, JobGroupResponse destination, JobGroupScheduleResponse? destMember, ResolutionContext context)
        {
            var schedule = esppConfigService.GetEsppScheduleDto(source.Id);

            if (schedule == null)
            {
                logger.LogError($"Не смог замапить расписание, так как оно null. JobGroupId: {source.Id}");
                return null;
            }

            var response = new JobGroupScheduleResponse
            {
                Timezone = settingsFromDb.ScheduleTimezone,
                TypeSchedule = mapper.Map<EsppScheduleTypeScheduleResponse>(schedule.TypeSchedule),
                Values = mapper.Map<List<EsppScheduleValResponse>>(schedule.Values).OrderBy(t => t.Order).ToList()
            };

            return response;
        }
    }
}
