"""Phase 13.3 — Clinic Management tests."""
from __future__ import annotations

import pytest

from app.events.publisher import get_event_publisher
from app.events.types import HealthcareEventType
from app.tests.conftest import TENANT_A, tenant_headers
from app.validators.clinic_management import validate_clinic_policy_windows
from shared.exceptions import AppError


async def _seed_clinic(client):
    headers = tenant_headers(TENANT_A)
    clinic = await client.post(
        "/api/v1/clinics",
        headers=headers,
        json={"code": "CLN133", "name": "Admin Clinic", "status": "active"},
    )
    assert clinic.status_code == 201
    clinic_id = clinic.json()["id"]
    doctor = await client.post(
        "/api/v1/doctors",
        headers=headers,
        json={
            "user_id": "doc-133",
            "clinic_id": clinic_id,
            "code": "DOC133",
            "display_name": "Dr Admin",
        },
    )
    assert doctor.status_code == 201
    return clinic_id, doctor.json()["id"]


def test_clinic_policy_validator():
    validate_clinic_policy_windows(booking_lead_time_hours=24, cancellation_window_hours=12)
    with pytest.raises(AppError) as exc:
        validate_clinic_policy_windows(booking_lead_time_hours=12, cancellation_window_hours=24)
    assert exc.value.error_code == "invalid_policy_windows"


@pytest.mark.asyncio
async def test_clinic_management_crud(client):
    clinic_id, doctor_id = await _seed_clinic(client)
    headers = tenant_headers(TENANT_A)

    service = await client.post(
        "/api/v1/clinic-services",
        headers=headers,
        json={
            "clinic_id": clinic_id,
            "code": "SVC1",
            "name": "Consultation",
            "duration_minutes": 30,
        },
    )
    assert service.status_code == 201

    staff = await client.post(
        "/api/v1/staff-assignments",
        headers=headers,
        json={
            "clinic_id": clinic_id,
            "doctor_id": doctor_id,
            "code": "STAFF1",
            "role_code": "attending",
        },
    )
    assert staff.status_code == 201

    policy = await client.post(
        "/api/v1/clinic-policies",
        headers=headers,
        json={
            "clinic_id": clinic_id,
            "code": "POL1",
            "name": "Booking Policy",
            "kind": "booking",
            "booking_lead_time_hours": 48,
            "cancellation_window_hours": 24,
        },
    )
    assert policy.status_code == 201

    hours = await client.post(
        "/api/v1/operating-hours-policies",
        headers=headers,
        json={
            "clinic_id": clinic_id,
            "code": "HRS1",
            "name": "Weekday Hours",
            "weekly_hours": {"monday": {"open": "08:00", "close": "17:00"}},
        },
    )
    assert hours.status_code == 201

    events = {e.event_type for e in get_event_publisher().published}
    assert HealthcareEventType.CLINIC_SERVICE_CREATED.value in events
    assert HealthcareEventType.STAFF_ASSIGNMENT_CREATED.value in events


@pytest.mark.asyncio
async def test_phase_133_capabilities(client):
    caps = await client.get("/capabilities")
    assert caps.json()["features"]["clinic_management"] is True
