"""Tests for the Compute Engine emulator."""

import json


def test_create_and_get_instance(client):
    resp = client.post(
        "/compute/v1/projects/test-proj/zones/us-central1-a/instances",
        json={"name": "test-vm", "machineType": "e2-micro"},
    )
    assert resp.status_code == 200
    data = resp.get_json()
    assert data["status"] == "DONE"

    resp = client.get("/compute/v1/projects/test-proj/zones/us-central1-a/instances/test-vm")
    assert resp.status_code == 200
    vm = resp.get_json()
    assert vm["name"] == "test-vm"
    assert vm["status"] == "RUNNING"


def test_list_instances(client):
    client.post(
        "/compute/v1/projects/test-proj/zones/us-central1-a/instances",
        json={"name": "vm-1"},
    )
    client.post(
        "/compute/v1/projects/test-proj/zones/us-central1-a/instances",
        json={"name": "vm-2"},
    )
    resp = client.get("/compute/v1/projects/test-proj/zones/us-central1-a/instances")
    data = resp.get_json()
    assert len(data["items"]) == 2


def test_delete_instance(client):
    client.post(
        "/compute/v1/projects/test-proj/zones/us-central1-a/instances",
        json={"name": "doomed-vm"},
    )
    resp = client.delete("/compute/v1/projects/test-proj/zones/us-central1-a/instances/doomed-vm")
    assert resp.status_code == 200

    resp = client.get("/compute/v1/projects/test-proj/zones/us-central1-a/instances/doomed-vm")
    assert resp.status_code == 404


def test_create_network(client):
    resp = client.post(
        "/compute/v1/projects/test-proj/global/networks",
        json={"name": "my-vpc", "autoCreateSubnetworks": False},
    )
    assert resp.status_code == 200

    resp = client.get("/compute/v1/projects/test-proj/global/networks/my-vpc")
    net = resp.get_json()
    assert net["name"] == "my-vpc"
    assert net["autoCreateSubnetworks"] is False


def test_create_firewall(client):
    resp = client.post(
        "/compute/v1/projects/test-proj/global/firewalls",
        json={
            "name": "allow-http",
            "allowed": [{"IPProtocol": "tcp", "ports": ["80"]}],
            "sourceRanges": ["0.0.0.0/0"],
        },
    )
    assert resp.status_code == 200

    resp = client.get("/compute/v1/projects/test-proj/global/firewalls/allow-http")
    fw = resp.get_json()
    assert fw["name"] == "allow-http"
    assert len(fw["allowed"]) == 1


def test_get_instance_404(client):
    resp = client.get("/compute/v1/projects/test-proj/zones/us-central1-a/instances/nope")
    assert resp.status_code == 404


def test_zone_operation(client):
    resp = client.get("/compute/v1/projects/test-proj/zones/us-central1-a/operations/fake-op")
    assert resp.status_code == 200
    data = resp.get_json()
    assert data["status"] == "DONE"
