using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace ColaFlow.Modules.ProjectManagement.IntegrationTests.Infrastructure;

/// <summary>
/// Helper class for generating JWT tokens in tests
/// </summary>
public static class TestAuthHelper
{
    private const string SecretKey = "test-secret-key-for-integration-tests-minimum-32-characters";
    private const string Issuer = "ColaFlow.Test";
    private const string Audience = "ColaFlow.Test";

    public static string GenerateJwtToken(Guid userId, Guid tenantId, string tenantSlug, string email, string role = "Member")
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.UTF8.GetBytes(SecretKey);

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
                new Claim("sub", userId.ToString()),
                new Claim("tenant_id", tenantId.ToString()),
                new Claim("tenantId", tenantId.ToString()),
                new Claim("tenantSlug", tenantSlug),
                new Claim("email", email),
                new Claim("role", role)
            }),
            Expires = DateTime.UtcNow.AddHours(1),
            Issuer = Issuer,
            Audience = Audience,
            SigningCredentials = new SigningCredentials(
                new SymmetricSecurityKey(key),
                SecurityAlgorithms.HmacSha256Signature)
        };

        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }

    public static void AddAuthHeader(this HttpClient client, string token)
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    }

    public static void AddAuthHeader(this HttpClient client, Guid userId, Guid tenantId, string tenantSlug, string email, string role = "Member")
    {
        var token = GenerateJwtToken(userId, tenantId, tenantSlug, email, role);
        client.AddAuthHeader(token);
    }
}
