using Microsoft.EntityFrameworkCore;
using Silk_Road_Api.DatabaseContext;

namespace Silk_Road_Api.Repositories;

public class Repository : RepositoryBase, IRepository
{
    public Repository(SilkRoadApiContext context) : base(context)
    {
    }

    public async Task AddAsync<T>(T entity)
    {
        await _context.AddAsync(entity);
    }

    public void Update<T>(T entity) where T : class
    {
        var trackedEntity = _context.Entry(entity);
        trackedEntity.State = EntityState.Modified;
        _context.Update(entity);
    }

    public void UpdateRange<T>(List<T> entities) where T : class
    {
        _context.UpdateRange(entities);
    }

    public async Task<bool> SaveChangesAsync()
    {
        var saved = false;
        int numberOfRetries = 0;
        do
        {
            try
            {
                await _context.SaveChangesAsync();
                saved = true;
            }
            catch (DbUpdateConcurrencyException ex)
            {
                foreach (var entry in ex.Entries)
                {
                    await entry.ReloadAsync();
                }
                numberOfRetries++;
            }
        }
        while (!saved && numberOfRetries < 3);
        return saved;
    }

    public void Delete<T>(T entity) where T : class
    {
        _context.Remove(entity);
    }

}
