using Microsoft.EntityFrameworkCore;

namespace BibliotekaWspolna;

public class SerwisNorthwind : ISerwisNorthwind
{
  private readonly NorthwindContext db;

  public SerwisNorthwind(NorthwindContext db)
  {
    this.db = db;
  }

  public Task<List<Customer>> PobierzKlientowAsync()
  {
    return db.Customers.ToListAsync();
  }

  public Task<List<Customer>> PobierzKlientowAsync(string country)
  {
    return db.Customers.Where(c => c.Country == country).ToListAsync();
  }

  public Task<Customer?> PobierzKlientaAsync(string id)
  {
    return db.Customers.FirstOrDefaultAsync
      (c => c.CustomerId == id);
  }

  public Task<Customer> UtworzKlientaAsync(Customer c)
  {
    db.Customers.Add(c);
    db.SaveChangesAsync();
    return Task.FromResult(c);
  }

  public Task<Customer> AktualizujKlientaAsync(Customer c)
  {
    db.Entry(c).State = EntityState.Modified;
    db.SaveChangesAsync();
    return Task.FromResult(c);
  }

  public Task UsunKlientaAsync(string id)
  {
    Customer? customer = db.Customers.FirstOrDefaultAsync
      (c => c.CustomerId == id)?.Result;

    if (customer == null)
    {
      return Task.CompletedTask;
    }
    else
    {
      db.Customers.Remove(customer);
      return db.SaveChangesAsync();
    }
  }
}
