using Sandbox;
using System;
using System.Text;

namespace GravCoin;

public static class PlayerSaveHasher
{
	private const ulong FnvOffsetBasis = 14695981039346656037UL;
	private const ulong FnvPrime = 1099511628211UL;
	private const string GlobalSaveSecret = "s&money_core_v1_x89!";

	public static string ComputeHex( byte[] data )
	{
		data ??= Array.Empty<byte>();

		ulong hash = FnvOffsetBasis;
		for ( int i = 0; i < data.Length; i++ )
		{
			hash ^= data[i];
			hash *= FnvPrime;
		}

		return hash.ToString( "X16" );
	}

	public static string ComputePlayerSaveHex( byte[] playerDataJson )
	{
		string json = playerDataJson is null
			? ""
			: Encoding.UTF8.GetString( playerDataJson );

		return ComputePlayerSaveHex( json );
	}

	public static string ComputePlayerSaveHex( string playerDataJson )
	{
		string payload = string.Concat( playerDataJson ?? "", ResolveLocalSteamId(), GlobalSaveSecret );
		return ComputeHex( Encoding.UTF8.GetBytes( payload ) );
	}

	private static string ResolveLocalSteamId()
	{
		var localConnection = Connection.Local;
		if ( localConnection is not null )
		{
			ulong localSteamId = localConnection.SteamId.ValueUnsigned;
			if ( localSteamId != 0UL )
				return localSteamId.ToString();
		}

		ulong gameSteamId = Game.SteamId.ValueUnsigned;
		if ( gameSteamId != 0UL )
			return gameSteamId.ToString();

		return "0";
	}
}
