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

namespace Gremlin_BlazorServer.Services
{
	public class AccountService
	{
		private readonly GremlinContext gremlinContext;

		public AccountService(GremlinContext gC) => gremlinContext = gC;

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

		public async Task<List<Account>> GetAllAccountsAsync() => await gremlinContext.Accounts.ToListAsync();

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

		public async Task<Account> GetAccountAsync(uint accountId)
		{
			Account? account = await gremlinContext.Accounts.FirstOrDefaultAsync(account => account.AccountId.Equals(accountId));
			return account == null ? new Account() : account;
		}

		public async Task<bool> UpdateAccountAsync(Account account)
		{
			_ = gremlinContext.Accounts.Update(account);
			_ = await gremlinContext.SaveChangesAsync();
			return true;
		}

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