
using Marco.Pms.DataAccess.Data;
using Marco.Pms.Model.Employees;
using Marco.Pms.Model.Mapper;
using Marco.Pms.Model.ViewModels.Employee;
using MarcoBMS.Services.Service;
using Microsoft.CodeAnalysis;
using Microsoft.EntityFrameworkCore;

namespace MarcoBMS.Services.Helpers
{
    public class EmployeeHelper
    {
        private readonly ApplicationDbContext _context;
        private readonly ILoggingService _logger;
        public EmployeeHelper(ApplicationDbContext context, ILoggingService logger)
        {
            _context = context;
            _logger = logger;
        }
        public async Task<Employee> GetEmployeeByID(Guid EmployeeID)
        {

            return await _context.Employees.Include(e => e.JobRole).FirstOrDefaultAsync(e => e.Id == EmployeeID) ?? new Employee { };
        }

        public async Task<Employee> GetEmployeeByApplicationUserID(string ApplicationUserID)
        {
            try
            {
                var result = await _context.Employees.Where(c => c.ApplicationUserId == ApplicationUserID && c.IsActive == true).ToListAsync();

                return await _context.Employees.Include(e => e.ApplicationUser).Where(c => c.ApplicationUserId == ApplicationUserID && c.ApplicationUser != null && c.IsActive == true).SingleOrDefaultAsync() ?? new Employee { };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occured while fetching employee by application user ID {ApplicationUserId}", ApplicationUserID);
                return new Employee();
            }
        }

        public async Task<List<EmployeeVM>> SearchEmployeeByProjectId(Guid TenentId, string searchString, Guid? ProjectId)
        {
            try
            {
                List<EmployeeVM> result = new List<EmployeeVM>();
                if (ProjectId != null)
                {

                    result = await (from pa in _context.ProjectAllocations.Where(c => c.ProjectId == ProjectId)
                                    join em in _context.Employees.Where(c => c.TenantId == TenentId && c.IsActive == true).Include(fp => fp.JobRole) // Include Feature
                    on pa.EmployeeId equals em.Id
                                    where (em.FirstName != null ? em.FirstName.ToLower().Contains(searchString.ToLower()) : false) || (em.LastName != null ? em.LastName.ToLower().Contains(searchString.ToLower()) : false)
                                    select em.ToEmployeeVMFromEmployee()
                                       )
                        .ToListAsync();

                }
                else
                {
                    result = await _context.Employees.Where(c => c.TenantId == TenentId && c.IsActive == true &&
                            ((c.FirstName != null ? c.FirstName.ToLower().Contains(searchString.ToLower()) : false) || (c.LastName != null ? c.LastName.ToLower().Contains(searchString.ToLower()) : false))).Include(fp => fp.JobRole)
                            .Select(c => c.ToEmployeeVMFromEmployee()).ToListAsync();
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occoured while filtering employees by string {SearchString} or project {ProjectId}", searchString, ProjectId ?? Guid.Empty);
                return new List<EmployeeVM>();
            }
        }

        public async Task<List<EmployeeVM>> GetEmployeeByProjectId(Guid tenantId, Guid? projectId, bool ShowInActive)
        {
            try
            {
                List<EmployeeVM> result = new List<EmployeeVM>();
                if (projectId.HasValue)
                {
                    var employeeIds = await _context.ProjectAllocations
                    .Where(pa => projectId == pa.ProjectId && pa.IsActive && pa.TenantId == tenantId)
                    .Select(pa => pa.EmployeeId)
                    .Distinct()
                    .ToListAsync();

                    result = await _context.Employees
                        .Include(fp => fp.JobRole)
                        .Where(e => employeeIds.Contains(e.Id) && e.IsActive && e.TenantId == tenantId)
                        .Select(e => e.ToEmployeeVMFromEmployee())
                        .Distinct()
                        .ToListAsync();

                }
                else if (ShowInActive)
                {
                    result = await _context.Employees.Where(c => c.TenantId == tenantId && c.IsActive == false).Include(fp => fp.JobRole)
                            .Select(c => c.ToEmployeeVMFromEmployee()).ToListAsync();
                }
                else
                {
                    result = await _context.Employees.Where(c => c.TenantId == tenantId && c.IsActive == true).Include(fp => fp.JobRole)
                            .Select(c => c.ToEmployeeVMFromEmployee()).ToListAsync();
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occured while featching list of employee by project ID {ProjectId}", projectId ?? Guid.Empty);
                return new List<EmployeeVM>();
            }
        }
    }
}

