from __future__ import annotations

from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool

from app.api.feedback import FeedbackCreate, create_feedback, delete_feedback, feedback_detail, feedback_list
from app.models import Base
from app.models.admin import Admin
from app.models.chat import ChatMessage, ChatSession
from app.models.user import User


def test_feedback_binds_target_answer_and_exposes_context() -> None:
    engine = create_engine("sqlite:///:memory:", connect_args={"check_same_thread": False}, poolclass=StaticPool)
    Base.metadata.create_all(engine)
    with Session(engine) as db:
        user = User(id=1, phone="13800000000", name="测试用户")
        admin = Admin(id=1, username="admin", password="hash", name="管理员", is_super_admin=1, must_change_password=0)
        db.add_all([user, admin]); db.flush()
        session = ChatSession(id=1, user_id=user.id, title="测试会话", message_count=2)
        db.add(session); db.flush()
        question = ChatMessage(id=1, session_id=session.id, user_id=user.id, role="user", content="问题", message_status="FINISHED")
        answer = ChatMessage(id=2, session_id=session.id, user_id=user.id, role="assistant", content="回答", message_status="FINISHED")
        db.add_all([question, answer]); db.commit()

        created = create_feedback(FeedbackCreate(messageId=answer.id, content="这条回答不准确"), db=db, user=user)["data"]
        listed = feedback_list(readStatus="unread", page=1, pageSize=20, db=db, _admin=admin)["data"]
        assert listed["total"] == 1
        detail = feedback_detail(created["id"], db=db, admin=admin)["data"]
        assert detail["messageId"] == answer.id
        assert [item["content"] for item in detail["messages"]] == ["问题", "回答"]
        assert detail["messages"][-1]["isTarget"] is True
        delete_feedback(created["id"], db=db, admin=admin)
        assert feedback_list(readStatus="all", page=1, pageSize=20, db=db, _admin=admin)["data"]["total"] == 0
