using Microsoft.EntityFrameworkCore;
using MTWorkHR.Core.Entities;
using MTWorkHR.Core.IDto;
using MTWorkHR.Core.IRepositories;
using MTWorkHR.Infrastructure.Entities;
using MTWorkHR.Infrastructure.DBContext;
using MTWorkHR.Core.Entities.User;

namespace MTWorkHR.Infrastructure.Repositories
{
    public class OrderRequestRepository : Repository<OrderRequest>, IOrderRequestRepository
    {
        private readonly DbSet<OrderRequest> dbSet;
        public OrderRequestRepository(HRDataContext context) : base(context)
        {
            dbSet = context.Set<OrderRequest>();

        }
        public async Task<OrderRequest> GetByIdWithAllChildren(long id)
        {
            return await dbSet
                .Include(x => x.OrderType)
                .Include(x=> x.LeaveType)
                .Include(x => x.BusinessTripExpenses).ThenInclude(x=> x.Attachments)
                .Include(x => x.ServiceCertificate)
                .Include(x => x.OrderAttachments)
                .Include(x => x.OverTimeDays).ThenInclude(x=> x.OverTimeAttachment)
                .AsNoTracking()
                .FirstOrDefaultAsync(x => x.Id == id);
        }

        public async Task<OrderRequest> GetByIdWithTypes(long id)
        {
            return await dbSet
                .Include(x => x.OrderType)
                .Include(x => x.LeaveType)
                .AsNoTracking()
                .FirstOrDefaultAsync(x => x.Id == id);
        }

        public async Task<Tuple<IQueryable<OrderRequest>, int>> GetAllWithChildrenAsync()
        {
            var query = dbSet.Include(x => x.OrderType).Include(x=> x.LeaveType).AsNoTracking().AsQueryable();
            var total = await query.CountAsync();

            return new Tuple<IQueryable<OrderRequest>, int>(query, total);
        }

        public async Task<Tuple<IQueryable<OrderRequest>, int>> GetAllUserOrdersAsync(string userId, long contractId)
        {
            var query = dbSet.Include(x => x.OrderType).Include(x => x.LeaveType).Where(a=> a.RequestingEmployeeId == userId && a.ContractId == contractId).AsNoTracking().AsQueryable();
            var total = await query.CountAsync();

            return new Tuple<IQueryable<OrderRequest>, int>(query, total);
        }
    }
}
