using Amazon.S3.Model.Internal.MarshallTransformations; using BMA.EHR.Application.Common.Interfaces; using BMA.EHR.Domain.Models.Base; using BMA.EHR.Domain.Models.HR; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using System.Security.Claims; namespace BMA.EHR.Application.Repositories { public class GenericRepository : IGenericRepository where T : class { #region " Field " private readonly IApplicationDBContext _dbContext; private readonly DbSet _dbSet; private readonly IHttpContextAccessor _httpContextAccessor; #endregion #region " Constructor and Destructor " public GenericRepository(IApplicationDBContext dbContext, IHttpContextAccessor httpContextAccessor) { _dbContext = dbContext; _dbSet = _dbContext.Set(); _httpContextAccessor = httpContextAccessor; } #endregion #region " Properties " protected string? UserId => _httpContextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; protected string? FullName => _httpContextAccessor?.HttpContext?.User?.FindFirst("name")?.Value; protected bool? IsPlacementAdmin => _httpContextAccessor?.HttpContext?.User?.IsInRole("placement1"); #endregion #region " Methods " public async Task GetProfileOrganizationAsync(string citizenId) { try { var pf = await _dbContext.Set() .Where(x => x.CitizenId == citizenId) .Where(x => x.ProfileType.ToLower().Trim() == "officer" && x.IsActive && !x.IsLeave) .FirstOrDefaultAsync(); return pf == null || pf.Oc == null ? Guid.Empty : pf.OcId!.Value; } catch { throw; } } public async Task CheckIsActiveOfficerAsync(string citizenId) { try { var pf = await _dbContext.Set() .Where(x => x.CitizenId == citizenId) .Where(x => x.ProfileType.ToLower().Trim() == "officer" && x.IsActive && !x.IsLeave) .FirstOrDefaultAsync(); return pf != null; } catch { throw; } } public virtual async Task> GetAllAsync() { return await _dbSet.ToListAsync(); } public virtual async Task GetByIdAsync(S id) { return await _dbSet.FindAsync(id); } public virtual async Task AddAsync(T entity) { if (entity is EntityBase) { (entity as EntityBase).CreatedUserId = UserId!; (entity as EntityBase).CreatedFullName = FullName!; (entity as EntityBase).CreatedAt = DateTime.Now; } await _dbSet.AddAsync(entity); await _dbContext.SaveChangesAsync(); return entity; } public virtual async Task UpdateAsync(T entity) { if (entity is EntityBase) { (entity as EntityBase).LastUpdateUserId = UserId!; (entity as EntityBase).LastUpdateFullName = FullName!; (entity as EntityBase).LastUpdatedAt = DateTime.Now; } _dbSet.Update(entity); await _dbContext.SaveChangesAsync(); return entity; } public virtual async Task DeleteAsync(T entity) { _dbSet.Remove(entity); await _dbContext.SaveChangesAsync(); } #endregion } }