using System; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using BlueWest.Data; using Microsoft.EntityFrameworkCore; namespace BlueWest.WebApi.EF { internal static class CountryDbExtensions { internal static (bool, Country) NotFound() => (false, null); internal static (bool, string, Country) ErrorMessage(string message) => (false, message, null); internal static (bool, string, Country) Success(bool success, Country country) => (success, "1", null); internal static (bool, Country) UpdateCountry( this CountryDbContext dbContext, CountryUpdate countryUpdate, int countryId) { var country = dbContext.Countries.FirstOrDefault(x => x.Id == countryId); if (country == null) return NotFound(); country.Update(countryUpdate); dbContext.Countries.Update(country); var result = dbContext.SaveChanges() >= 0; return (result, country); } internal static async Task GetCountryByIdAsync(this DbSet countries, int countryId) => await countries.FirstOrDefaultAsync(x => x.Id == countryId); internal static (bool, string, Country) AddCurrency( this CountryDbContext dbContext, int countryId, CurrencyCreate currencyCreate) { var country = dbContext.Countries.FirstOrDefault(d => d.Code == countryId); // Check if currency exists if (country == null) return (false, "Country Not found.", null); // Creates new currency var newCurrency = new Currency(currencyCreate); country.Currencies.Add(newCurrency); var success = dbContext.SaveChanges() >= 0; return Success(success, country); } internal static (bool, string, Country) AddCurrency( this CountryDbContext dbContext, int countryId, CurrencyCreate currencyCreate, Expression>[] duplicationValidations) { var country = dbContext.Countries.FirstOrDefault(d => d.Code == countryId); // Check if currency exists if (country == null) return (false, $"{nameof(country)} Not found.", null); // Check if there's currency with the same code foreach (var duplicationValidation in duplicationValidations) { var currencyToGet = dbContext.Currencies.FirstOrDefault(duplicationValidation); if (currencyToGet != null) return ErrorMessage($"Duplication Validation failed: {nameof(duplicationValidation.Body.ToString)}"); } // Creates new currency var newCurrency = new Currency(currencyCreate); country.Currencies.Add(newCurrency); var success = dbContext.SaveChanges() >= 0; return Success(success, country); } } }