using Gremlin_BlazorServer.Data.DBClasses;
using Gremlin_BlazorServer.Data.EntityClasses;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;

namespace Gremlin_BlazorServer.Services
{
	public class ProductService
	{
		private readonly GremlinContext gremlinContext;
		public ProductService(GremlinContext gC) => gremlinContext = gC;

		public void ConfigureServices(IServiceCollection services) => services.AddDbContext<GremlinContext>(ServiceLifetime.Scoped);

		public async Task<List<Product>> GetAllProductsAsync() => await gremlinContext.Products.ToListAsync();

		public async Task<bool> InsertProductAsync(Product Product)
		{
			try
			{
				_ = await gremlinContext.Products.AddAsync(Product);
				_ = await gremlinContext.SaveChangesAsync();
				return true;
			}
			catch (Exception exception)
			{
				Debug.WriteLine(exception.Message);
				return false;
			}
		}

		public async Task<Product?> GetProductAsync(string productNumber)
		{
			Product? Product = await gremlinContext.Products.FirstOrDefaultAsync(Product => Product.ProductNumber.Equals(productNumber));
			return Product;
		}

		public async Task<bool> UpdateProductAsync(Product Product)
		{
			_ = gremlinContext.Products.Update(Product);
			_ = await gremlinContext.SaveChangesAsync();
			return true;
		}

		public async Task<bool> DeleteProductAsync(Product Product)
		{
			_ = gremlinContext.Remove(Product);
			_ = await gremlinContext.SaveChangesAsync();
			return true;
		}
	}
}
