using AutoMapper;
using DigitalData.UserManager.Application.Contracts;
using DigitalData.UserManager.Application.DTOs.UserRep;
using DigitalData.UserManager.Domain.Entities;
using DigitalData.UserManager.Application.Contracts.Repositories;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using DigitalData.Core.Abstraction.Application.DTO;

namespace DigitalData.UserManager.Application.Services
{
    [Obsolete("Use MediatR")]
    public class UserRepService : BaseService<IUserRepRepository, UserRepCreateDto, UserRepReadDto, UserRep>, IUserRepService
    {
        private readonly IStringLocalizer<Resource>? _localizer;
        public UserRepService(IUserRepRepository repository, IMapper mapper, IStringLocalizer<Resource>? localizer = null) : base(repository, mapper)
        {
            _localizer = localizer;
        }

        public async Task<DataResult<IEnumerable<UserRepReadDto>>> ReadAllAsync(bool withUser = false, bool withRepGroup = false, bool withGroup = false, bool withRepUser = false, int? userId = null, int? groupId = null)
        {
            var urs = await _repository.ReadAllAsync(withUser: withUser, withRepGroup: withRepGroup, withGroup: withGroup, withRepUser: withRepUser, userId: userId, groupId: groupId);
            var urReadDTOs = _mapper.Map<IEnumerable<UserRepReadDto>>(urs);
            return Result.Success(urReadDTOs);
        }

        public override async Task<DataResult<UserRepReadDto>> CreateAsync(UserRepCreateDto createDto)
            // XOR control
            => (createDto.ValidFrom is null && createDto.ValidTo is not null) || (createDto.ValidFrom is not null && createDto.ValidTo is null)
                ? Result.Fail<UserRepReadDto>().Notice(LogLevel.None, Flag.DataIntegrityIssue, _localizer?[Key.DateRangeNotXNOR].Value)
            //date range control
                : (createDto.ValidFrom > createDto.ValidTo)
                ? Result.Fail<UserRepReadDto>().Notice(LogLevel.None, Flag.DataIntegrityIssue, _localizer?[Key.InvalidDateRange].Value)
                : await base.CreateAsync(createDto);        
    }
}