#nullable enable

using Insight.Database;
using PlanTempus.Core.CommandQueries;
using PlanTempus.Core.Database;

namespace PlanTempus.Components.Accounts.ConfirmEmail;

public class ConfirmEmailHandler(IDatabaseOperations databaseOperations) : ICommandHandler<ConfirmEmailCommand>
{
	public async Task<CommandResponse> Handle(ConfirmEmailCommand command)
	{
		using var db = databaseOperations.CreateScope(nameof(ConfirmEmailHandler));

		var sql = @"
			UPDATE system.accounts
			SET email_confirmed = true
			WHERE email = @Email AND security_stamp = @Token";

		var affectedRows = await db.Connection.ExecuteSqlAsync(sql, new
		{
			command.Email,
			command.Token
		});

		if (affectedRows == 0)
		{
			throw new InvalidTokenException();
		}

		return new CommandResponse(command.CorrelationId, command.GetType().Name, command.TransactionId);
	}
}

public class InvalidTokenException : Exception
{
	public InvalidTokenException() : base("Invalid or expired verification token")
	{
	}
}
