"""Phase 12.7 Connectors API / tenant / validation tests."""
from __future__ import annotations

import pytest

from app.events.publisher import get_event_publisher
from app.events.types import HospitalityEventType
from app.tests.conftest import TENANT_A, TENANT_B, tenant_headers


@pytest.mark.asyncio
async def test_connector_dispatch_sent_when_registration_active(client):
    h = tenant_headers(TENANT_A)

    registration = await client.post(
        "/api/v1/connector-registrations",
        json={
            "kind": "delivery",
            "code": "delivery-1",
            "name": "Delivery Connector",
            "status": "active",
        },
        headers=h,
    )
    assert registration.status_code == 201, registration.text
    registration_id = registration.json()["id"]
    assert registration.json()["status"] == "active"

    dispatch = await client.post(
        "/api/v1/connector-dispatches",
        json={
            "registration_id": registration_id,
            "event_type": "order.created",
            "payload_ref": "ref-1",
        },
        headers=h,
    )
    assert dispatch.status_code == 201, dispatch.text
    assert dispatch.json()["status"] == "sent"
    assert dispatch.json()["response_json"]["ok"] is True

    published = {e.event_type for e in get_event_publisher().published}
    assert HospitalityEventType.CONNECTOR_REGISTRATION_CREATED.value in published
    assert HospitalityEventType.CONNECTOR_DISPATCH_CREATED.value in published


@pytest.mark.asyncio
async def test_connector_dispatch_fails_when_registration_not_active(client):
    h = tenant_headers(TENANT_A)

    registration = await client.post(
        "/api/v1/connector-registrations",
        json={
            "kind": "accounting",
            "code": "accounting-draft",
            "name": "Accounting Connector",
        },
        headers=h,
    )
    assert registration.status_code == 201, registration.text
    assert registration.json()["status"] == "draft"
    registration_id = registration.json()["id"]

    dispatch = await client.post(
        "/api/v1/connector-dispatches",
        json={
            "registration_id": registration_id,
            "event_type": "invoice.created",
        },
        headers=h,
    )
    assert dispatch.status_code == 201, dispatch.text
    assert dispatch.json()["status"] == "failed"
    assert dispatch.json()["response_json"]["ok"] is False


@pytest.mark.asyncio
async def test_connector_registration_code_unique_per_tenant(client):
    h = tenant_headers(TENANT_A)

    first = await client.post(
        "/api/v1/connector-registrations",
        json={"kind": "crm", "code": "crm-1", "name": "CRM Connector"},
        headers=h,
    )
    assert first.status_code == 201, first.text

    duplicate = await client.post(
        "/api/v1/connector-registrations",
        json={"kind": "crm", "code": "crm-1", "name": "CRM Connector Dup"},
        headers=h,
    )
    assert duplicate.status_code == 409


@pytest.mark.asyncio
async def test_connector_registration_tenant_isolation(client):
    h = tenant_headers(TENANT_A)

    registration = await client.post(
        "/api/v1/connector-registrations",
        json={"kind": "loyalty", "code": "loyalty-iso", "name": "Loyalty Connector"},
        headers=h,
    )
    assert registration.status_code == 201, registration.text
    registration_id = registration.json()["id"]

    denied = await client.get(
        f"/api/v1/connector-registrations/{registration_id}",
        headers=tenant_headers(TENANT_B),
    )
    assert denied.status_code == 404


@pytest.mark.asyncio
async def test_connector_dispatch_missing_registration_returns_404(client):
    import uuid

    h = tenant_headers(TENANT_A)
    missing = await client.post(
        "/api/v1/connector-dispatches",
        json={
            "registration_id": str(uuid.uuid4()),
            "event_type": "test.event",
        },
        headers=h,
    )
    assert missing.status_code == 404


@pytest.mark.asyncio
async def test_capabilities_phase_12_7(client):
    resp = await client.get("/capabilities")
    assert resp.status_code == 200
    body = resp.json()
    assert body["features"]["delivery_integration"] is True
    assert body["features"]["accounting_integration"] is True
    assert body["features"]["crm_integration"] is True
    assert body["features"]["loyalty_integration"] is True
    assert body["features"]["communication_integration"] is True
    assert body["features"]["website_integration"] is True
    assert body["features"]["ai"] is False
