from __future__ import annotations

from typing import Any

import pytest

from sync_state_machine.datasource.task_result import TaskStatus
from sync_state_machine.domain.contract.api_handler import ContractApiHandler
from sync_state_machine.domain.contract.sync_node import ContractSyncNode


class _MockApiClient:
    def __init__(self) -> None:
        self.requests: list[dict[str, Any]] = []

    async def request(self, method: str, endpoint: str, **kwargs: Any) -> dict[str, Any]:
        self.requests.append({"method": method, "endpoint": endpoint, **kwargs})
        return {"code": 200, "message": "OK", "data": {"biz_id": "contract-created-1"}}


@pytest.mark.asyncio
async def test_contract_create_passes_name_and_qt_code_to_api() -> None:
    handler = ContractApiHandler()
    handler.api_client = _MockApiClient()
    handler.set_poll_mode("sync")

    node = ContractSyncNode(
        node_id="contract-node-1",
        data={
            "id": "contract-local-1",
            "project_id": "project-1",
            "name": "电缆采购合同",
            "short_name": "电缆采购合同",
            "code": "QT",
            "contract_type": "product",
            "currency": "CNY",
            "manager_name": "张三",
            "manager_phone": "13800000000",
            "sign_company": "测试供应商",
            "company_id": "company-1",
            "sign_date": "2026-03-01",
            "credit_code": "91350000123456789X",
            "total_price": 1200.5,
            "sub_name": None,
        },
        context={"project_id": "project-1"},
    )

    results = await handler.create_all([node])

    assert len(results) == 1
    assert results[0].status == TaskStatus.SUCCESS
    assert results[0].data_id == "contract-created-1"

    request = handler.api_client.requests[0]
    assert request["endpoint"] == "/contract/create"
    assert request["data"]["data"]["name"] == "电缆采购合同"
    assert request["data"]["data"]["code"] == "QT"
    assert request["data"]["data"]["project_id"] == "project-1"