# backend/tests/test_integration.py
"""checker.py → purchase_manager 연동 통합 테스트"""
import sys, os
import sqlite3

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "app"))

import pytest
from unittest.mock import patch


def _make_mem_conn():
    conn = sqlite3.connect(":memory:")
    conn.row_factory = sqlite3.Row
    return conn


def test_check_results_triggers_purchase_check():
    """check_results_for_draw가 purchase 체크도 트리거하는지 검증"""
    import db
    import backend.app.purchase_manager as pm

    mem = _make_mem_conn()
    with patch("db._conn", return_value=mem):
        db.init_db()

        # 당첨번호 삽입
        mem.execute(
            "INSERT INTO draws (drw_no, drw_date, n1, n2, n3, n4, n5, n6, bonus) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (1124, "2026-03-28", 1, 2, 3, 4, 5, 6, 7)
        )
        mem.execute(
            "INSERT INTO draws (drw_no, drw_date, n1, n2, n3, n4, n5, n6, bonus) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (1125, "2026-04-04", 10, 20, 30, 35, 40, 44, 15)
        )
        mem.commit()

        # 1125회차 대상 구매 등록
        db.add_purchase(
            draw_no=1125, amount=1000, sets=1,
            numbers=[[10, 20, 30, 1, 2, 3]],
            is_real=True, source_strategy="combined",
        )

    # purchase_manager의 check_purchases_for_draw��� 직접 호출하여 연동 검증
    with patch("db._conn", return_value=mem), \
         patch("backend.app.purchase_manager.get_draw", side_effect=lambda drw: db.get_draw(drw)), \
         patch("backend.app.purchase_manager.get_purchases", side_effect=lambda **kw: db.get_purchases(**kw)), \
         patch("backend.app.purchase_manager.update_purchase_results", side_effect=lambda *a, **kw: db.update_purchase_results(*a, **kw)), \
         patch("backend.app.purchase_manager.upsert_strategy_performance", side_effect=lambda **kw: db.upsert_strategy_performance(**kw)):
        purchase_count = pm.check_purchases_for_draw(1125)

    assert purchase_count == 1

    # purchase가 체크되었는지 확인
    with patch("db._conn", return_value=mem):
        purchases = db.get_purchases(draw_no=1125)
    assert purchases[0]["checked"] == 1
    assert purchases[0]["results"][0]["correct"] == 3  # 10, 20, 30 맞음

    mem.close()
