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

namespace PARR.API.MappingProfiles.Resolvers
{
    public class TemplateScheduleResolver : IValueResolver<Template, TemplateResponse, EsppScheduleResponse?>
    {
        private readonly IEsppSchTypeConfigRepository esppConfigService;
        private readonly ILogger<TemplateScheduleResolver> logger;
        private readonly IMapper mapper;
        private readonly SettingsFromDb settingsFromDb;
        private readonly IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetService;

        public TemplateScheduleResolver(
            IEsppSchTypeConfigRepository esppConfigService,
            ILogger<TemplateScheduleResolver> logger,
            IMapper mapper,
            SettingsFromDb settingsFromDb,
            IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetService
            )
        {
            this.esppConfigService = esppConfigService;
            this.logger = logger;
            this.mapper = mapper;
            this.settingsFromDb = settingsFromDb;
            this.scheduleResponseAreaTimeOffsetService = scheduleResponseAreaTimeOffsetService;
        }

        public EsppScheduleResponse? Resolve(Template source, TemplateResponse destination, EsppScheduleResponse? destMember, ResolutionContext context)
        {
            var schedule = esppConfigService.GetEsppScheduleDto(source.Job!.GroupId);

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

            var response = new EsppScheduleResponse
            {
                //NextRun = source.ApplicationsInWork!.NextRun,
                //LastRun = source.ApplicationsInWork.LastRun,
                NextRun = source.NextRun,
                LastRun = source.LastRun,
                // Timezone = settingsFromDb.ScheduleTimezone,
                Timezone = scheduleResponseAreaTimeOffsetService.GetDefault.EsppValue,
                TypeSchedule = mapper.Map<EsppScheduleTypeScheduleResponse>(schedule.TypeSchedule),
                Values = mapper.Map<List<EsppScheduleValResponse>>(schedule.Values).OrderBy(t => t.Order).ToList()
            };

            return response;
        }
    }
}
