using Microsoft.AspNetCore.Identity;
using MyOffice.Web.Identity.Domain;
using MyOffice.Web.Identity.Repositories;

namespace MyOffice.Tests.Auth;

public class PasswordHasherTests
{
	private readonly PasswordHasher _hasher = new();
	private readonly ApplicationUser<Guid> _user = new() { Id = Guid.NewGuid(), UserName = "test@example.com" };

	[Fact]
	public void HashPassword_then_verify_succeeds_with_identity_format()
	{
		var hash = _hasher.HashPassword(_user, "P@ssw0rd!");

		Assert.Equal(PasswordVerificationResult.Success, _hasher.VerifyHashedPassword(_user, hash, "P@ssw0rd!"));
	}

	[Fact]
	public void VerifyHashedPassword_fails_for_wrong_password()
	{
		var hash = _hasher.HashPassword(_user, "P@ssw0rd!");

		Assert.Equal(PasswordVerificationResult.Failed, _hasher.VerifyHashedPassword(_user, hash, "wrong"));
	}

	[Fact]
	public void HashPassword_produces_distinct_hashes_due_to_salt()
	{
		var a = _hasher.HashPassword(_user, "same");
		var b = _hasher.HashPassword(_user, "same");

		Assert.NotEqual(a, b);
	}

	[Fact]
	public void VerifyHashedPassword_legacy_hash_returns_rehash_needed()
	{
		var legacy = PasswordHasher.HashLegacyForTests("legacy-secret");

		Assert.Equal(
			PasswordVerificationResult.SuccessRehashNeeded,
			_hasher.VerifyHashedPassword(_user, legacy, "legacy-secret"));
	}

	[Fact]
	public void VerifyHashedPassword_legacy_wrong_password_fails()
	{
		var legacy = PasswordHasher.HashLegacyForTests("legacy-secret");

		Assert.Equal(
			PasswordVerificationResult.Failed,
			_hasher.VerifyHashedPassword(_user, legacy, "nope"));
	}
}
