"""Integration tests for ResolutionOutputGenerator."""
import pytest
from unittest.mock import AsyncMock, patch
from httpx import AsyncClient

from app.models.ai_session import AISession
from app.models.session_resolution_output import SessionResolutionOutput


@pytest.mark.asyncio
@patch("app.services.resolution_output_generator._call_ai")
async def test_generate_all_creates_three_outputs(
    mock_call_ai, client: AsyncClient, test_user, auth_headers, test_db
):
    """generate_all creates PSA notes, KB article, and client summary."""
    mock_call_ai.return_value = ("Generated content here", 100, 50)

    session = AISession(
        user_id=test_user["user_data"]["id"],
        account_id=test_user["user_data"]["account_id"],
        session_type="guided",
        intake_type="free_text",
        intake_content={"text": "test"},
        status="resolved",
        confidence_tier="guided",
        conversation_messages=[
            {"role": "user", "content": "DNS not working"},
            {"role": "assistant", "content": "Fixed by flushing DNS cache"},
        ],
        resolution_summary="Flushed DNS cache",
    )
    test_db.add(session)
    await test_db.flush()

    from app.services.resolution_output_generator import ResolutionOutputGenerator
    gen = ResolutionOutputGenerator(test_db)
    outputs = await gen.generate_all(session.id)

    assert len(outputs) == 3
    types = {o.output_type for o in outputs}
    assert types == {"psa_ticket_notes", "knowledge_base", "client_summary"}
    assert all(o.status == "draft" for o in outputs)
    assert mock_call_ai.call_count == 3


@pytest.mark.asyncio
async def test_edit_output(client: AsyncClient, test_user, auth_headers, test_db):
    """Editing an output stores edited_content."""
    session = AISession(
        user_id=test_user["user_data"]["id"],
        account_id=test_user["user_data"]["account_id"],
        session_type="guided",
        intake_type="free_text",
        intake_content={"text": "test"},
        status="resolved",
        confidence_tier="guided",
        conversation_messages=[],
        resolution_summary="Fixed it",
    )
    test_db.add(session)
    await test_db.flush()

    output = SessionResolutionOutput(
        session_id=session.id,
        account_id=session.account_id,
        output_type="psa_ticket_notes",
        generated_content="Original notes",
        status="draft",
        generated_by_model="claude-sonnet-4-6",
    )
    test_db.add(output)
    await test_db.flush()

    from app.services.resolution_output_generator import ResolutionOutputGenerator
    gen = ResolutionOutputGenerator(test_db)
    edited = await gen.edit_output(output.id, "My edited notes")

    assert edited.edited_content == "My edited notes"
