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

namespace PARR.API.MappingProfiles.Resolvers
{
    public class ApplicationInWorkScheduleResolver : IValueResolver<ApplicationsInWork, ApplicationInWorkResponse, ApplicationInWorkScheduleResponse?>
    {
        private readonly IEsppSchTypeConfigService esppConfigService;
        private readonly ILogger<ApplicationInWorkScheduleResolver> logger;
        private readonly IMapper mapper;
        private readonly SettingsFromDb settingsFromDb;

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

        public ApplicationInWorkScheduleResponse? Resolve(ApplicationsInWork source, ApplicationInWorkResponse destination, ApplicationInWorkScheduleResponse? destMember, ResolutionContext context)
        {
            var schedule = esppConfigService.GetEsppScheduleDto(source.Id);

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

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

            return response;
        }
    }
}
