#nullable enable
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.DTOs;
using API.Entities;
using API.Entities.Enums;
using API.Extensions;
using API.Extensions.QueryExtensions;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
namespace API.Data.Repositories;
public interface IAppUserReadingProfileRepository
{
///
/// Return the given profile if it belongs the user
///
///
///
///
Task GetUserProfile(int userId, int profileId);
///
/// Returns all reading profiles for the user
///
///
///
Task> GetProfilesForUser(int userId, bool skipImplicit = false);
///
/// Returns all reading profiles for the user
///
///
///
Task> GetProfilesDtoForUser(int userId, bool skipImplicit = false);
///
/// Is there a user reading profile with this name (normalized)
///
///
///
///
Task IsProfileNameInUse(int userId, string name);
void Add(AppUserReadingProfile readingProfile);
void Update(AppUserReadingProfile readingProfile);
void Remove(AppUserReadingProfile readingProfile);
void RemoveRange(IEnumerable readingProfiles);
}
public class AppUserReadingProfileRepository(DataContext context, IMapper mapper): IAppUserReadingProfileRepository
{
public async Task GetUserProfile(int userId, int profileId)
{
return await context.AppUserReadingProfiles
.Where(rp => rp.AppUserId == userId && rp.Id == profileId)
.FirstOrDefaultAsync();
}
public async Task> GetProfilesForUser(int userId, bool skipImplicit = false)
{
return await context.AppUserReadingProfiles
.Where(rp => rp.AppUserId == userId)
.WhereIf(skipImplicit, rp => rp.Kind != ReadingProfileKind.Implicit)
.ToListAsync();
}
///
/// Returns all Reading Profiles for the User
///
///
///
public async Task> GetProfilesDtoForUser(int userId, bool skipImplicit = false)
{
return await context.AppUserReadingProfiles
.Where(rp => rp.AppUserId == userId)
.WhereIf(skipImplicit, rp => rp.Kind != ReadingProfileKind.Implicit)
.ProjectTo(mapper.ConfigurationProvider)
.ToListAsync();
}
public async Task IsProfileNameInUse(int userId, string name)
{
var normalizedName = name.ToNormalized();
return await context.AppUserReadingProfiles
.Where(rp => rp.NormalizedName == normalizedName && rp.AppUserId == userId)
.AnyAsync();
}
public void Add(AppUserReadingProfile readingProfile)
{
context.AppUserReadingProfiles.Add(readingProfile);
}
public void Update(AppUserReadingProfile readingProfile)
{
context.AppUserReadingProfiles.Update(readingProfile).State = EntityState.Modified;
}
public void Remove(AppUserReadingProfile readingProfile)
{
context.AppUserReadingProfiles.Remove(readingProfile);
}
public void RemoveRange(IEnumerable readingProfiles)
{
context.AppUserReadingProfiles.RemoveRange(readingProfiles);
}
}