"""Health, capability, migration, tenant isolation, security tests."""
from __future__ import annotations

import uuid

import pytest
from httpx import AsyncClient

from app.tests.conftest import TENANT_A, TENANT_B, tenant_headers


@pytest.mark.asyncio
async def test_health(client: AsyncClient):
    res = await client.get("/health")
    assert res.status_code == 200
    body = res.json()
    assert body["status"] == "ok"
    assert body["service"] == "communication-service"
    assert "sms" in body["channels"]


@pytest.mark.asyncio
async def test_capabilities(client: AsyncClient):
    res = await client.get("/capabilities")
    assert res.status_code == 200
    body = res.json()
    assert body["independent"] is True
    assert body["requires_other_modules"] is False
    assert "provider_framework" in body["features"]
    assert "otp" in body["features"]
    channels = {c["channel"] for c in body["channels"]}
    assert "sms" in channels
    assert "email" in channels


@pytest.mark.asyncio
async def test_tenant_required_for_providers(client: AsyncClient):
    res = await client.get("/api/v1/providers")
    assert res.status_code == 400


@pytest.mark.asyncio
async def test_tenant_isolation(client: AsyncClient):
    a = tenant_headers(TENANT_A)
    b = tenant_headers(TENANT_B)
    create = await client.post(
        "/api/v1/providers",
        headers=a,
        json={
            "name": "A Mock",
            "provider_kind": "mock",
            "channel": "sms",
            "priority": 10,
            "credentials": {},
        },
    )
    assert create.status_code == 201
    provider_id = create.json()["id"]

    other = await client.get(f"/api/v1/providers/{provider_id}", headers=b)
    assert other.status_code == 404

    own = await client.get(f"/api/v1/providers/{provider_id}", headers=a)
    assert own.status_code == 200


def test_migration_revision_exists():
    from pathlib import Path

    versions = Path(__file__).resolve().parents[2] / "alembic" / "versions"
    files = list(versions.glob("0001_*.py"))
    assert files
    text = files[0].read_text(encoding="utf-8")
    assert "0001_initial" in text


def test_permissions_security_tree():
    from app.permissions.definitions import ALL_PERMISSIONS

    assert all(p.startswith("communication.") for p in ALL_PERMISSIONS)
