using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using ColaFlow.Modules.ProjectManagement.Application.Common.Interfaces;

namespace ColaFlow.Modules.ProjectManagement.Infrastructure.Services;

/// <summary>
/// Implementation of ITenantContext that retrieves tenant ID from JWT claims
/// </summary>
public sealed class TenantContext : ITenantContext
{
    private readonly IHttpContextAccessor _httpContextAccessor;

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

    public Guid GetCurrentTenantId()
    {
        var httpContext = _httpContextAccessor.HttpContext;
        if (httpContext == null)
            throw new InvalidOperationException("HTTP context is not available");

        var user = httpContext.User;
        var tenantClaim = user.FindFirst("tenant_id") ?? user.FindFirst("tenantId");

        if (tenantClaim == null || !Guid.TryParse(tenantClaim.Value, out var tenantId))
            throw new UnauthorizedAccessException("Tenant ID not found in claims");

        return tenantId;
    }
}
