import pytest
import base64
import json
import jwt
from cloud.auth.sso.saml_flow import generate_auth_request, parse_saml_response, map_saml_to_jwt

@pytest.fixture
def saml_config():
    return {
        "entity_id": "brynq-app",
        "sso_url": "https://idp.example.com/sso",
        "attribute_mapping": {
            "email": "userPrincipalName",
            "name": "displayName",
            "groups": "memberOf"
        }
    }

def test_generate_auth_request(saml_config):
    b64_req = generate_auth_request(saml_config)
    assert b64_req
    decoded = base64.b64decode(b64_req).decode("utf-8")
    assert "<samlp:AuthnRequest" in decoded
    assert "brynq-app" in decoded
    assert "https://idp.example.com/sso" in decoded

def test_parse_saml_response_invalid(saml_config):
    res = parse_saml_response(base64.b64encode(b"garbage").decode("utf-8"), saml_config)
    assert res is None

def test_parse_saml_response_valid_mock(saml_config):
    mock_data = {
        "userPrincipalName": "test@company.com",
        "displayName": "Test User",
        "memberOf": ["users", "brynq-admins"]
    }
    b64_res = base64.b64encode(json.dumps(mock_data).encode("utf-8")).decode("utf-8")
    parsed = parse_saml_response(b64_res, saml_config)
    assert parsed is not None
    assert parsed["email"] == "test@company.com"
    assert parsed["name"] == "Test User"
    assert "brynq-admins" in parsed["groups"]

def test_map_saml_to_jwt():
    saml_user = {
        "email": "admin@company.com",
        "name": "Admin User",
        "groups": ["brynq-admins"]
    }
    team_id = "team-123"
    
    token = map_saml_to_jwt(saml_user, team_id)
    assert token
    
    decoded = jwt.decode(token, "dev-jwt-secret", algorithms=["HS256"])
    assert decoded["sub"] == "admin@company.com"
    assert decoded["team_id"] == "team-123"
    assert decoded["role"] == "admin"
