using Marco.Pms.DataAccess.Data;
using Marco.Pms.Model.Employees;
using Marco.Pms.Model.Entitlements;
using Marco.Pms.Model.TenantModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;

namespace MarcoBMS.Services.Helpers
{
    public class UserHelper
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ApplicationDbContext _context;

        public UserHelper(UserManager<ApplicationUser> userManager, IHttpContextAccessor httpContextAccessor, ApplicationDbContext context)
        {
            _userManager = userManager;
            _httpContextAccessor = httpContextAccessor;
            _context = context;
        }

        public Guid GetTenantId()
        {
            var tenant = _httpContextAccessor.HttpContext?.User.FindFirst("TenantId")?.Value;
            return (tenant != null ? Guid.Parse(tenant) : Guid.Empty);
        }
        public Guid GetCurrentOrganizationId()
        {
            var tenant = _httpContextAccessor.HttpContext?.User.FindFirst("OrganizationId")?.Value;
            return (tenant != null ? Guid.Parse(tenant) : Guid.Empty);
        }
        public async Task<Tenant?> GetCurrentTenant()
        {
            var tenantId = _httpContextAccessor.HttpContext?.User.FindFirst("TenantId")?.Value;
            if (tenantId != null)
            {
                return await _context.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == Guid.Parse(tenantId));
            }
            return null;
        }

        public async Task<IdentityUser?> GetCurrentUserAsync()
        {
            var userId = _httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (string.IsNullOrEmpty(userId))
                return null;
            var user = await _userManager.FindByEmailAsync(userId);
            return user;  //await _userManager.FindByIdAsync(userId);
        }
        public async Task<Employee> GetCurrentEmployeeAsync()
        {
            var user = await GetCurrentUserAsync();
            if (user == null) return new Employee { };
            var Employee = await _context.Employees.AsNoTracking().Include(a => a.ApplicationUser).Include(e => e.JobRole).FirstOrDefaultAsync(e => e.ApplicationUserId == user.Id && e.IsActive);
            return Employee ?? new Employee { };
        }

        public async Task<object?> GetCurrentUserProfileAsync()
        {

            var user = await GetCurrentUserAsync();
            return user == null ? null : new
            {
                user.Id,
                user.UserName,
                user.Email,
                user.PhoneNumber
            };
        }

        public async Task<IdentityUser?> GetRegisteredUser(string email)
        {
            IdentityUser? user = await _userManager.FindByEmailAsync(email);
            return user;
        }
    }
}
