using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using WorkClub.Application.Interfaces;

namespace WorkClub.Infrastructure.Services;

public class TenantProvider : ITenantProvider
{
    private readonly IHttpContextAccessor _httpContextAccessor;

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

    public string GetTenantId()
    {
        var tenantId = _httpContextAccessor.HttpContext?.Items["TenantId"] as string;
        if (string.IsNullOrEmpty(tenantId))
        {
            throw new InvalidOperationException("Tenant context is not available");
        }

        return tenantId;
    }

    public string GetUserRole()
    {
        var httpContext = _httpContextAccessor.HttpContext;
        if (httpContext?.User == null)
        {
            throw new InvalidOperationException("User context is not available");
        }

        var tenantId = GetTenantId();
        var clubsClaim = httpContext.User.FindFirst("clubs")?.Value;

        if (string.IsNullOrEmpty(clubsClaim))
        {
            throw new InvalidOperationException("User does not have clubs claim");
        }

        var clubsDict = JsonSerializer.Deserialize<Dictionary<string, string>>(clubsClaim);
        if (clubsDict == null || !clubsDict.TryGetValue(tenantId, out var role))
        {
            throw new InvalidOperationException($"User is not a member of tenant {tenantId}");
        }

        return role;
    }
}
