using ColaFlow.Modules.Identity.Domain.Aggregates.Tenants;
using Microsoft.AspNetCore.Http;

namespace ColaFlow.Modules.Identity.Infrastructure.Services;

/// <summary>
/// Tenant context implementation (Scoped lifetime - one instance per request)
/// </summary>
public class TenantContext : ITenantContext
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private TenantId? _tenantId;
    private string? _tenantSlug;

    public TenantContext(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
        InitializeFromHttpContext();
    }

    public TenantId? TenantId => _tenantId;
    public string? TenantSlug => _tenantSlug;
    public bool IsSet => _tenantId != null;

    public void SetTenant(TenantId tenantId, string tenantSlug)
    {
        _tenantId = tenantId;
        _tenantSlug = tenantSlug;
    }

    public void Clear()
    {
        _tenantId = null;
        _tenantSlug = null;
    }

    /// <summary>
    /// Initialize from HTTP Context (extract tenant info from JWT Claims)
    /// </summary>
    private void InitializeFromHttpContext()
    {
        var httpContext = _httpContextAccessor.HttpContext;
        if (httpContext?.User?.Identity?.IsAuthenticated == true)
        {
            // Extract tenant_id from JWT Claims
            var tenantIdClaim = httpContext.User.FindFirst("tenant_id");
            var tenantSlugClaim = httpContext.User.FindFirst("tenant_slug");

            if (tenantIdClaim != null && Guid.TryParse(tenantIdClaim.Value, out var tenantIdGuid))
            {
                _tenantId = TenantId.Create(tenantIdGuid);
                _tenantSlug = tenantSlugClaim?.Value;
            }
        }
    }
}
