using System.Linq.Expressions;

namespace DigitalData.Core.Application.Interfaces.Repository;

public static class Extensions
{
    #region Create
    public static Task<TEntity> CreateAsync<TEntity, TDto>(this IRepository<TEntity> repository, TDto dto, CancellationToken ct = default)
    {
        var entity = repository.Mapper.Map(dto);
        return repository.CreateAsync(entity, ct);
    }

    public static Task<IEnumerable<TEntity>> CreateAsync<TEntity, TDto>(this IRepository<TEntity> repository, IEnumerable<TDto> dtos, CancellationToken ct = default)
    {
        var entities = dtos.Select(dto => repository.Mapper.Map(dto));
        return repository.CreateAsync(entities, ct);
    }
    #endregion

    #region Read
    public static async Task<TEntity?> ReadFirstOrDefaultAsync<TEntity>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>>? expression = null)
        => (await repository.ReadAllAsync(expression)).FirstOrDefault();

    public static async Task<TEntity> ReadFirstAsync<TEntity>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>>? expression = null)
        => (await repository.ReadAllAsync(expression)).First();

    public static async Task<TEntity?> ReadSingleOrDefaultAsync<TEntity>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>>? expression = null)
        => (await repository.ReadAllAsync(expression)).SingleOrDefault();

    public static async Task<TEntity> ReadSingleAsync<TEntity>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>>? expression = null)
        => (await repository.ReadAllAsync(expression)).Single();
    #endregion
}
