"""Tests for the IAM emulator."""


def test_create_and_get_service_account(client):
    resp = client.post(
        "/v1/projects/test-proj/serviceAccounts",
        json={
            "accountId": "my-app",
            "serviceAccount": {"displayName": "My App SA"},
        },
    )
    assert resp.status_code == 200
    sa = resp.get_json()
    assert sa["email"] == "my-app@test-proj.iam.gserviceaccount.com"
    assert sa["displayName"] == "My App SA"

    resp = client.get(
        f"/v1/projects/test-proj/serviceAccounts/{sa['email']}"
    )
    assert resp.status_code == 200
    assert resp.get_json()["email"] == sa["email"]


def test_list_service_accounts(client):
    client.post(
        "/v1/projects/test-proj/serviceAccounts",
        json={"accountId": "sa-one"},
    )
    client.post(
        "/v1/projects/test-proj/serviceAccounts",
        json={"accountId": "sa-two"},
    )
    resp = client.get("/v1/projects/test-proj/serviceAccounts")
    data = resp.get_json()
    assert len(data["accounts"]) == 2


def test_create_project_role(client):
    resp = client.post(
        "/v1/projects/test-proj/roles",
        json={
            "roleId": "customViewer",
            "role": {
                "title": "Custom Viewer",
                "includedPermissions": ["compute.instances.list"],
            },
        },
    )
    assert resp.status_code == 200
    role = resp.get_json()
    assert role["name"] == "projects/test-proj/roles/customViewer"
    assert "compute.instances.list" in role["includedPermissions"]


def test_predefined_roles(client):
    resp = client.get("/v1/roles")
    roles = resp.get_json()["roles"]
    names = [r["name"] for r in roles]
    assert "roles/viewer" in names
    assert "roles/editor" in names
