"""Test inbox unread memo functionality."""
import pytest
from fastapi.testclient import TestClient
from server import app

@pytest.fixture
def client():
    with TestClient(app) as c:
        yield c

def test_inbox_unread_count(client, authenticated_headers):
    """Test that /users/{id}/inbox/unread_count returns correct count."""
    # Create some memos with is_read=False
    client.post("/api/v1/memos", json={
        "content": "Unread memo 1",
        "visibility": "PRIVATE",
        "workspace_id": "PERSONAL",
        "is_read": False
    }, headers=authenticated_headers)
    client.post("/api/v1/memos", json={
        "content": "Unread memo 2",
        "visibility": "PRIVATE",
        "workspace_id": "PERSONAL",
        "is_read": False
    }, headers=authenticated_headers)
    # Create a read memo
    client.post("/api/v1/memos", json={
        "content": "Read memo",
        "visibility": "PRIVATE",
        "workspace_id": "PERSONAL",
        "is_read": True
    }, headers=authenticated_headers)

    # Get unread count
    response = client.get("/api/v1/users/1/inbox/unread_count", headers=authenticated_headers)
    assert response.status_code == 200
    data = response.json()
    assert "unread_count" in data
    assert data["unread_count"] >= 2  # At least 2 unread

def test_inbox_list_unread_memos(client, authenticated_headers):
    """Test that /users/{id}/inbox/memos returns only unread memos."""
    # Clear existing and create test data
    response = client.get("/api/v1/users/1/inbox/memos", headers=authenticated_headers)
    assert response.status_code == 200
    memos = response.json()

    # All returned memos should have is_read=False
    for memo in memos:
        assert memo.get("is_read") is False, f"Memo {memo['id']} should be unread"

def test_mark_memo_as_read(client, authenticated_headers):
    """Test marking a memo as read via PATCH /memos/{id}."""
    # Create an unread memo
    create_response = client.post("/api/v1/memos", json={
        "content": "Memo to mark as read",
        "visibility": "PRIVATE",
        "workspace_id": "PERSONAL",
        "is_read": False
    }, headers=authenticated_headers)
    memo_id = create_response.json()["id"]

    # Verify it's unread
    unread_response = client.get("/api/v1/users/1/inbox/unread_count", headers=authenticated_headers)
    initial_count = unread_response.json()["unread_count"]

    # Mark as read
    patch_response = client.patch(f"/api/v1/memos/{memo_id}", json={
        "is_read": True
    }, headers=authenticated_headers)
    assert patch_response.status_code == 200
    updated_memo = patch_response.json()
    assert updated_memo.get("is_read") is True

    # Verify count decreased
    after_response = client.get("/api/v1/users/1/inbox/unread_count", headers=authenticated_headers)
    after_count = after_response.json()["unread_count"]
    assert after_count == initial_count - 1

def test_webhook_creates_unread_memo(client):
    """Test that inbound webhook creates memo with is_read=False."""
    workspace_id = "AI_SALES_CRM"
    webhook_payload = {
        "title": "Test Webhook",
        "body": "This is a test webhook payload",
        "tags": ["webhook", "test"]
    }

    # Note: webhook endpoint does NOT require auth and path is /inbound_webhooks (not /api/v1/inbound_webhooks)
    response = client.post(
        f"/inbound_webhooks/{workspace_id}",
        json=webhook_payload
    )
    assert response.status_code == 200, f"Failed: {response.text}"
    data = response.json()
    memo = data["memo"]

    # Verify memo was created in correct workspace with is_read=False
    assert memo["workspace_id"] == workspace_id
    assert memo.get("is_read") is False

def test_webhook_formats_payload_to_markdown(client):
    """Test that webhook properly formats various payloads to markdown."""
    # Test with title + body
    response1 = client.post("/inbound_webhooks/PERSONAL", json={
        "title": "My Title",
        "body": "My body content"
    })
    response_data1 = response1.json()
    # Webhook returns {"success": True, "memo": {...}, "message": "..."}
    if "memo" in response_data1:
        memo1 = response_data1["memo"]
    else:
        print(f"Unexpected response: {response_data1}")
        raise AssertionError(f"Response missing 'memo' key: {response_data1}")
    assert "# My Title" in memo1["content"]
    assert "My body content" in memo1["content"]

    # Test with only arbitrary fields
    response2 = client.post("/inbound_webhooks/PERSONAL", json={
        "event_type": "user.signup",
        "user_id": 123,
        "timestamp": "2024-01-01"
    })
    response_data2 = response2.json()
    if "memo" in response_data2:
        memo2 = response_data2["memo"]
    else:
        print(f"Unexpected response: {response_data2}")
        raise AssertionError(f"Response missing 'memo' key: {response_data2}")
    assert "**event_type**: user.signup" in memo2["content"]
    assert "**user_id**: 123" in memo2["content"]
