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.Global;

namespace MTWorkHR.Infrastructure.Repositories
{
    public class ContractRepository : Repository<Contract>, IContractRepository
    {
        private readonly DbSet<Contract> dbSet;
        private readonly DbSet<TeamUser> dbSet2;
        public ContractRepository(HRDataContext context) : base(context)
        {
            dbSet = context.Set<Contract>();
            dbSet2 = context.Set<TeamUser>();

        }
        public async Task<Contract> GetByIdWithAllChildren(long id)
        {
            return await dbSet
                .Include(x => x.ContractTasks)
                .Include(x => x.FixedAllowances)
                .Include(x => x.ProjectStages)
            //    .Include(x => x.WorkingDays)
                .FirstOrDefaultAsync(x => x.Id == id);
        }
        public async Task<Contract> GetLatestActiveContract(string userId)
        {
            return await dbSet
                .FirstOrDefaultAsync(x => x.UserId == userId 
                && x.ContractStatusId == (int)ContractStatusEnum.Approved
                && x.StartDate <= DateTime.UtcNow.Date
                && (x.EndDate == null || x.EndDate < DateTime.UtcNow.Date));
        }


        public async Task<Tuple<IQueryable<Contract>, int>> GetAllWithChildrenAsync()
        {
            var query = dbSet//.Join(x => x.TeamUser)
                .AsQueryable();




            var total = await query.CountAsync();

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

        public async Task<Tuple<IQueryable<Contract>, int>> GetAllWithTeamsAsync()
        {
            var query = dbSet//.Join(x => x.TeamUser)
              .AsQueryable();

            //var teamUsersList = dbSet2.Include(x => x.Team).ToList();
            var query2 = dbSet
                 .Join(
                     dbSet2.Include(x => x.Team),
                     c => c.UserId,
                     teamUser => teamUser.AssignedUserId,
                     (contract, teamUser) => new
                     {
                         Contract = contract,
                         Team = teamUser.Team.NameEn
                     }
                 )
                 .AsQueryable();




            var total = await query2.CountAsync();

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