using Microsoft.EntityFrameworkCore;
using Modules.User.Database.Database;
using Modules.User.Database.Database.Entities;
using System;
using System.Linq.Expressions;
using Modules.User.Application.Repositories;

namespace Modules.User.Database.Repositories;

public class AccountRepository(UserDbContext context) : IAccountRepository
{
    public async Task<bool> ExistsWithRoleAsync(int roleId, CancellationToken cancellationToken)
    {
        return await context.Accounts
            .SelectMany(q => q.Roles)
            .AsNoTracking()
            .AnyAsync(q => q.RoleId == roleId, cancellationToken);
    }

    public async Task<bool> ExistsWithDirectPermissionAsync(int permissionId, CancellationToken cancellationToken)
    {
        return await context.Accounts
            .SelectMany(q => q.Permissions)
            .AsNoTracking()
            .AnyAsync(q => q.PermissionId == permissionId, cancellationToken);
    }

    public async Task<Guid?> TryGetAccountIdByRefreshTokenAsync(string refreshToken, DateTime nowUtc,
        CancellationToken cancellationToken)
    {
        return await context.Sessions
            .Where(q => q.RefreshToken == refreshToken && q.ExpiredDate > nowUtc)
            .AsNoTracking()
            .Select(q => q.AccountId)
            .FirstOrDefaultAsync(cancellationToken);
    }
    
}