"""Assert mongosh insert scripts include Prisma-required fields (BSON Date, is_archived)."""

from unittest.mock import patch

import pytest


@pytest.fixture
def sample_stat_doc():
    return {
        "type": "broadband",
        "country": "United Kingdom",
        "operator": "TestOp",
        "operatorId": "507f1f77bcf86cd799439011",
        "period": "2025Q1",
        "tech": "FTTP",
        "channel": "Infrastructure",
        "domain": "Residential",
        "subscribers": 100,
        "is_estimate": False,
        "restated": False,
        "notes": None,
        "createdBy": "test",
    }


@pytest.fixture
def sample_source_doc():
    return {
        "operatorId": "507f1f77bcf86cd799439011",
        "year": 2025,
        "quarter": 1,
        "type": "report",
        "url": "https://example.com/x",
    }


def test_insert_one_statistic_includes_bson_dates_and_archived(sample_stat_doc):
    from point_topic_mcp.core.mongodb_utils import insert_one_statistic

    captured = []

    def fake_run(js: str, timeout: int = 15) -> str:
        captured.append(js)
        return '{"$oid":"507f1f77bcf86cd799439011"}'

    with (
        patch("point_topic_mcp.core.mongodb_utils._run_mongosh", side_effect=fake_run),
        patch.dict("os.environ", {"PT_RESEARCH_DATABASE_URI": "mongodb://localhost:27017/t"}, clear=False),
    ):
        insert_one_statistic(sample_stat_doc)

    js = captured[0]
    assert "const now = new Date()" in js
    assert "date: now" in js
    assert "createdAt: now" in js
    assert "updatedAt: now" in js
    assert "is_archived: false" in js


def test_insert_one_source_includes_bson_dates(sample_source_doc):
    from point_topic_mcp.core.mongodb_utils import insert_one_source

    captured = []

    def fake_run(js: str, timeout: int = 15) -> str:
        captured.append(js)
        return '{"$oid":"507f1f77bcf86cd799439012"}'

    with (
        patch("point_topic_mcp.core.mongodb_utils._run_mongosh", side_effect=fake_run),
        patch.dict("os.environ", {"PT_RESEARCH_DATABASE_URI": "mongodb://localhost:27017/t"}, clear=False),
    ):
        insert_one_source(sample_source_doc)

    js = captured[0]
    assert "const now = new Date()" in js
    assert "createdAt: now" in js
    assert "updatedAt: now" in js
