"""Tests for enterprise tier licensing infrastructure."""

import base64
import json
from datetime import datetime

from apiposture_pro.licensing.models import LicenseContext, LicenseFeature, LicenseType

ENTERPRISE_MOCK_JWT = (
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
    ".eyJ0aWVyIjoiZW50ZXJwcmlzZSIsImZlYXR1cmVzIjpbImRpZmYiLCJoaXN0b3J5Iiwi"
    "cmlzay1zY29yaW5nIiwib3dhc3AtcnVsZXMiLCJzZWNyZXRzIiwiY29tcGxpYW5jZS1yZX"
    "BvcnRzIiwiY29tcGxpYW5jZS1zY29yZSIsInN0YXJ0ZXIta2l0cyIsInJlbWVkaWF0aW9u"
    "LWd1aWRhbmNlIiwicG9saWN5LWVuZm9yY2VtZW50IiwicHItZ2F0ZSIsImF1ZGl0LXRyYWls"
    "Iiwib3BlcmF0b3ItYXR0cmlidXRpb24iXSwib3JnIjoiQWNtZSBDb3JwIiwic2VhdHMiOiIy"
    "IiwidHlwZSI6ImRldmVsb3BlciIsImV4cCI6OTk5OTk5OTk5OX0"
    ".fakesig"
)

PRO_REGRESSION_JWT = (
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
    ".eyJ0aWVyIjoicHJvIiwiZmVhdHVyZXMiOlsiZGlmZiIsImhpc3RvcnkiLCJyaXNrLXNjb3Jp"
    "bmciLCJvd2FzcC1ydWxlcyIsInNlY3JldHMiXSwib3JnIjoiQWNtZSBDb3JwIiwic2VhdHMi"
    "OiIyIiwidHlwZSI6ImRldmVsb3BlciIsImV4cCI6OTk5OTk5OTk5OX0"
    ".fakesig"
)


def _parse_jwt(token: str) -> LicenseContext:
    """Parse a JWT token into a LicenseContext (mirrors manager._parse_token)."""
    parts = token.split(".")
    assert len(parts) == 3, "JWT must have 3 parts"
    payload = parts[1]
    # Add base64 padding
    payload += "=" * (4 - len(payload) % 4)
    claims = json.loads(base64.b64decode(payload).decode())
    expires_at = datetime.utcfromtimestamp(claims["exp"])
    seats_raw = claims.get("seats", "1")
    seats = int(seats_raw) if isinstance(seats_raw, str) else int(seats_raw)
    return LicenseContext(
        license_key=claims.get("license_key", ""),
        tier=claims["tier"],
        features=claims.get("features", []),
        expires_at=expires_at,
        customer_name=claims.get("org", ""),
        customer_email="",
        organization=claims.get("org"),
        seats=seats,
        license_type=LicenseType.DEVELOPER,
    )


def test_enterprise_jwt_tier_is_enterprise():
    ctx = _parse_jwt(ENTERPRISE_MOCK_JWT)
    assert ctx.tier == "enterprise"


def test_enterprise_jwt_has_13_features():
    ctx = _parse_jwt(ENTERPRISE_MOCK_JWT)
    assert len(ctx.features) == 13


def test_is_pro_or_higher_true_for_enterprise():
    ctx = _parse_jwt(ENTERPRISE_MOCK_JWT)
    assert ctx.is_pro_or_higher is True


def test_is_pro_or_higher_true_for_pro():
    ctx = _parse_jwt(PRO_REGRESSION_JWT)
    assert ctx.is_pro_or_higher is True


def test_is_enterprise_or_higher_true_for_enterprise():
    ctx = _parse_jwt(ENTERPRISE_MOCK_JWT)
    assert ctx.is_enterprise_or_higher is True


def test_is_pro_or_higher_false_for_free():
    ctx = LicenseContext(
        license_key="",
        tier="free",
        features=[],
        expires_at=datetime(2099, 1, 1),
        customer_name="",
        customer_email="",
    )
    assert ctx.is_pro_or_higher is False


def test_is_enterprise_or_higher_false_for_pro():
    ctx = _parse_jwt(PRO_REGRESSION_JWT)
    assert ctx.is_enterprise_or_higher is False


def test_is_enterprise_or_higher_false_for_free():
    ctx = LicenseContext(
        license_key="",
        tier="free",
        features=[],
        expires_at=datetime(2099, 1, 1),
        customer_name="",
        customer_email="",
    )
    assert ctx.is_enterprise_or_higher is False


def test_status_display_shows_enterprise_for_enterprise_tier():
    ctx = _parse_jwt(ENTERPRISE_MOCK_JWT)
    assert ctx.tier.upper() == "ENTERPRISE"
    assert ctx.is_enterprise_or_higher is True


def test_pro_regression_full():
    ctx = _parse_jwt(PRO_REGRESSION_JWT)
    assert ctx.tier == "pro"
    assert ctx.is_pro_or_higher is True
    assert ctx.is_enterprise_or_higher is False
    assert len(ctx.features) == 5
    assert LicenseFeature.DIFF.value in ctx.features
