using Gremlin_BlazorServer.Data.DBClasses;
using Gremlin_BlazorServer.Data.EntityClasses;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;

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

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

		private Task<AuthenticationState> AuthenticationStateTask { get; set; } = default!;

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

		public async Task<List<RegisteredUser>> GetAllRegisteredUserAsync() => await gremlinContext.RegisteredUser.ToListAsync();

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

		public async Task<RegisteredUser?> GetRegisteredUserAsync(string registeredUserName)
		{
			return await gremlinContext.RegisteredUser.FirstOrDefaultAsync(rU => rU.UserName.Equals(registeredUserName)!);
		}

		public async Task<bool> UpdateRegisteredUserAsync(RegisteredUser registeredUser)
		{
			_ = gremlinContext.RegisteredUser.Update(registeredUser);
			_ = await gremlinContext.SaveChangesAsync();
			return true;
		}

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

		public async Task<bool> ValidateUserAsync(RegisteredUser registeredUser)
		{
			_ = await Task.Run(() => GetRegisteredUserAsync(registeredUser.UserName));
			AuthenticationState? authState = await AuthenticationStateTask;
			return authState is null ? false : authState.User.Identity.IsAuthenticated;
		}
	}
}