"""
Tests for GET /api/v1/sales/inquiries/count and inquiry tenant isolation (INDL-24).
"""
from datetime import datetime, timezone, timedelta

import pytest
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession

from src.apps.sales.models.contact_inquiry import ContactInquiry


LOG_CALL_URL = "/api/v1/sales/inquiries/log-call"
COUNT_URL = "/api/v1/sales/inquiries/count"

VALID_CALL_PAYLOAD = {
    "sender_name": "Inbox Count Tester",
    "sender_phone": "(613) 555-0177",
    "call_date": (datetime.now(timezone.utc) - timedelta(minutes=10)).isoformat(),
    "agent_name": "Test Agent",
    "notes": "Count endpoint test call.",
}


def _tenant_headers(token: str, tenant_id: str):
    return {"Authorization": f"Bearer {token}", "X-Tenant-ID": tenant_id}


@pytest.mark.asyncio
async def test_inquiry_count_reflects_new_inquiries(
    client: AsyncClient,
    db_session: AsyncSession,
    admin_token: str,
    test_account,
):
    """GET /inquiries/count returns the number of status='new' inquiries for the tenant."""
    before = await client.get(COUNT_URL, headers=_tenant_headers(admin_token, str(test_account.id)))
    assert before.status_code == 200
    before_count = before.json()["data"]["new"]

    await client.post(
        LOG_CALL_URL,
        json=VALID_CALL_PAYLOAD,
        headers=_tenant_headers(admin_token, str(test_account.id)),
    )

    after = await client.get(COUNT_URL, headers=_tenant_headers(admin_token, str(test_account.id)))
    assert after.status_code == 200
    assert after.json()["data"]["new"] == before_count + 1


@pytest.mark.asyncio
async def test_inquiry_count_requires_auth(client: AsyncClient, test_account):
    response = await client.get(COUNT_URL, headers={"X-Tenant-ID": str(test_account.id)})
    assert response.status_code == 401


@pytest.mark.asyncio
async def test_mark_as_read_updates_status(
    client: AsyncClient,
    db_session: AsyncSession,
    admin_token: str,
    test_account,
):
    """PATCH /{id} with status='read' updates the inquiry and is reflected in the count."""
    create_resp = await client.post(
        LOG_CALL_URL,
        json=VALID_CALL_PAYLOAD,
        headers=_tenant_headers(admin_token, str(test_account.id)),
    )
    inq_id = create_resp.json()["data"]["id"]

    before = (await client.get(COUNT_URL, headers=_tenant_headers(admin_token, str(test_account.id)))).json()["data"]["new"]

    patch_resp = await client.patch(
        f"/api/v1/sales/inquiries/{inq_id}",
        json={"status": "read"},
        headers=_tenant_headers(admin_token, str(test_account.id)),
    )
    assert patch_resp.status_code == 200
    assert patch_resp.json()["data"]["status"] == "read"

    after = (await client.get(COUNT_URL, headers=_tenant_headers(admin_token, str(test_account.id)))).json()["data"]["new"]
    assert after == before - 1


@pytest.mark.asyncio
async def test_inquiries_tenant_isolation(
    client: AsyncClient,
    db_session: AsyncSession,
    admin_token: str,
    test_account,
):
    """T-16: GET /inquiries from a different tenant returns 0 rows for this tenant's data."""
    from src.apps.tenants.models.account import Account
    from src.apps.auth.models.user import User
    from src.core.security import hash_password, create_access_token, build_token_payload

    other_account = Account(
        organization_name="Other Cemetery",
        subdomain="othercemetery-isolation-test",
        contact_email="admin@othercemetery.com",
        plan="starter",
        status="active",
    )
    db_session.add(other_account)
    await db_session.flush()

    other_admin = User(
        tenant_id=other_account.id,
        email="admin@othercemetery-isolation.com",
        password_hash=hash_password("Test1234"),
        first_name="Other",
        last_name="Admin",
        role="administrator",
        status="active",
    )
    db_session.add(other_admin)
    await db_session.flush()
    other_token = create_access_token(build_token_payload(other_admin, other_account))

    await client.post(
        LOG_CALL_URL,
        json=VALID_CALL_PAYLOAD,
        headers=_tenant_headers(admin_token, str(test_account.id)),
    )

    other_list = await client.get(
        "/api/v1/sales/inquiries",
        headers=_tenant_headers(other_token, str(other_account.id)),
    )
    assert other_list.status_code == 200
    other_names = [i["sender_name"] for i in other_list.json()["data"]]
    assert "Inbox Count Tester" not in other_names
