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

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

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

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

		public async Task<List<Contact>> GetAllContactsAsync() => await gremlinContext.Contacts.ToListAsync();

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

		public async Task<Contact> GetContactAsync(uint contactId)
		{
			Contact? contact = await gremlinContext.Contacts.FirstOrDefaultAsync(c => c.ContactId.Equals(contactId));
			return contact ?? new Contact();
		}

		public async Task<Contact> GetContactAsync(string lastName)
		{
			Contact? contact = await gremlinContext.Contacts.FirstOrDefaultAsync(c => c.LastName.Equals(lastName));
			return contact ?? new Contact();
		}

		public async Task<bool> UpdateContactAsync(Contact contact)
		{
			_ = gremlinContext.Contacts.Update(contact);
			_ = await gremlinContext.SaveChangesAsync();
			return true;
		}

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