using Silk_Road_Api.Models;

namespace Silk_Road_Api.Repositories;

public class MemoryManufacturerRepository : IRepository, IManufacturerRepository
{
    private readonly List<Manufacturer> _manufacturers = new List<Manufacturer>{
        new Manufacturer { id = 1, name = "Pfizer", address = "New York", contact ="contact@Pfizer.com"},
        new Manufacturer { id = 2, name = "Moderna", address = "New Jersey", contact ="contact@Moderna.com"}
    };

    public MemoryManufacturerRepository()
    {

    }

    public new async Task AddAsync<T>(T entity)
    {
        (entity as Manufacturer).id = _manufacturers.Max(d => d.id) + 1;
        _manufacturers.Add(entity as Manufacturer);
    }

    public new void Update<T>(T entity) where T : class
    {
        var manufacturerId = (entity as Manufacturer).id;
        var manufacturer = _manufacturers.FirstOrDefault(d => d.id == manufacturerId);
        if (manufacturer == null)
            throw new Exception("Manufacturer not found");
        manufacturer.name = (entity as Manufacturer).name;
        manufacturer.address = (entity as Manufacturer).address;
        manufacturer.contact = (entity as Manufacturer).contact;

    }

    public new void UpdateRange<T>(List<T> entities) where T : class
    {
        foreach (var entity in entities)
        {
            Update(entity);
        }
    }

    public new async Task<bool> SaveChangesAsync()
    {
        return true;
    }

    public new async Task<Manufacturer> GetAsync<T>(params object[] ids) where T : class
    {
        return _manufacturers.FirstOrDefault(d => d.id == (int)ids.FirstOrDefault());
    }

    public new IQueryable<T> AsQueryable<T>() where T : class
    {
        return _manufacturers.AsQueryable() as IQueryable<T>;
    }

    public new void Delete<T>(T entity) where T : class
    {
        if (!_manufacturers.Remove(entity as Manufacturer))
            throw new Exception("Failed to delete drug");
    }

    public IQueryable<Manufacturer> GetManufacturers()
    {
        return _manufacturers.AsQueryable();
    }

    public Task<Manufacturer> GetManufacturer(int id)
    {
        return Task.FromResult(_manufacturers.Where(d => d.id == id).FirstOrDefault());
    }

    public Task<int> GetManufacturerByName(string name)
    {
        return Task.FromResult(_manufacturers.Where(d => d.name == name).Select(d => d.id).FirstOrDefault());
    }

    public void GenerateManufacturers(int n = 5)
    {
        throw new NotImplementedException();
    }

    Task<T> IRepository.GetAsync<T>(params object[] ids)
    {
        throw new NotImplementedException();
    }

    public async Task<int> ExecuteCount(IQueryable<Manufacturer> query)
    {
        return query.Count();
    }
}
