using Microsoft.EntityFrameworkCore;
using Modules.User.Database.Database;
using System.Linq.Expressions;

namespace Modules.User.Database.Repositories;

public class UserRepository(UserDbContext context)
{
    private readonly UserDbContext _context = context;

    internal async Task<Guid> AddAsync(Database.Entities.User user)
    {
        _context.Users.Add(user);
        await _context.SaveChangesAsync();
        return user.Id;
    }

    internal async Task<bool> DeleteAsync(Guid userId)
    {
        var user = await _context.Users.FirstOrDefaultAsync(q => q.Id == userId);
        if (user != null)
        {
            user.Deleted = true;
            user.Account.Deleted = true;
            await _context.SaveChangesAsync();
            return true;
        }
        else return false;
    }

    internal async Task<Database.Entities.User?> GetFirstOrDefaultWhereAsync(Expression<Func<Database.Entities.User, bool>> predicate) =>
        await UserQuery().FirstOrDefaultAsync(predicate);

    internal async Task<Database.Entities.User> GetFirstWhereAsync(Expression<Func<Database.Entities.User, bool>> predicate) =>
        await UserQuery().FirstAsync(predicate);

    internal async Task UpdateUserAsync() => await _context.SaveChangesAsync();

    private IQueryable<Database.Entities.User> UserQuery() => _context.Users
        .Include(q => q.Account).ThenInclude(q => q.Sessions)
        .Include(q => q.RegionalSettings).AsQueryable();
}