"""Unit tests for terraform/onboarding (P20, REQ-184)."""

import subprocess
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parent.parent
ONBOARDING_DIR = ROOT / "terraform" / "onboarding"


def test_onboarding_terraform_dir_exists():
    """P20 (REQ-184): terraform/onboarding/ exists with main.tf + README."""
    assert ONBOARDING_DIR.is_dir()
    assert (ONBOARDING_DIR / "main.tf").is_file()
    assert (ONBOARDING_DIR / "README.md").is_file()


def test_onboarding_terraform_validates():
    """P20 (REQ-184): terraform validate passes for the onboarding module
    (offline-proven, D-114). Skipped if terraform is not installed."""
    if not subprocess.call(["which", "terraform"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0:
        pytest.skip("terraform not installed")
    rc = subprocess.call(
        ["terraform", "validate"],
        cwd=str(ONBOARDING_DIR),
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
    )
    assert rc == 0, "terraform validate failed for terraform/onboarding/"


def test_onboarding_main_tf_has_nova_tags():
    """P20 (REQ-184): the deploy role is tagged with nova:owner + nova:contract."""
    main_tf = (ONBOARDING_DIR / "main.tf").read_text()
    assert '"nova:owner"' in main_tf
    assert '"nova:contract"' in main_tf
    assert "aws_iam_role" in main_tf
    assert "lambda:InvokeFunctionUrl" in main_tf