using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MTWorkHR.Application.Identity;
using MTWorkHR.Application.Mapper;
using MTWorkHR.Application.Models;
using MTWorkHR.Core.Global;
using MTWorkHR.Core.IRepositories;
using MTWorkHR.Core.UnitOfWork;
using MTWorkHR.Infrastructure.Entities;
using MTWorkHR.Application.Services.Interfaces;
using MTWorkHR.Core.Email;
using MTWorkHR.Core.Entities;
using MTWorkHR.Infrastructure.UnitOfWorks;

namespace MTWorkHR.Application.Services
{
    public class OrderAllocationService : BaseService<OrderAllocation, OrderAllocationDto, OrderAllocationDto>, IOrderAllocationService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IUserService _user;
      
        public OrderAllocationService(IUnitOfWork unitOfWork, IUserService user) :base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _user = user;
        }


        public override async Task<OrderAllocationDto> GetById(long id)
        {
            var entity = await _unitOfWork.OrderAllocation.GetByIdWithAllChildren(id);
            var response = MapperObject.Mapper.Map<OrderAllocationDto>(entity);
            return response;
        }


        public async Task<OrderAllocationDto> CreateAllEmployees(OrderAllocationDto input)
        {
            try
            {
                var orderType = await _unitOfWork.OrderType.GetByIdAsync(input.OrderTypeId);
                var leaveType = input.LeaveTypeId.HasValue && input.LeaveTypeId > 0 ? await _unitOfWork.LeaveType.GetByIdAsync(input.LeaveTypeId.Value) : null;
                var employees = await _user.GetAllEmployees();
                var period = DateTime.UtcNow.Year;
                var allocations = new List<OrderAllocation>();
                foreach (var emp in employees)
                {
                    if (await _unitOfWork.OrderAllocation.AllocationExists(emp.Id, orderType.Id, input.LeaveTypeId,0, period))
                        continue;
                    allocations.Add(new OrderAllocation
                    {
                        EmployeeId = emp.Id,
                        OrderTypeId = orderType.Id,
                        LeaveTypeId = leaveType != null ? leaveType.Id : null,
                        NumberOfDays = leaveType != null ? leaveType.DefaultDays : orderType.DefaultDays,
                        Period = period
                    });
                }

                await _unitOfWork.OrderAllocation.AddRangeAsync(allocations);
                await _unitOfWork.CompleteAsync();

            }catch(Exception ex)
            {
                var msg = ex.Message;
            }
            return input;


        }
       



    }
}
