"""存储基类测试：先写元数据到真实表，再上传文件。"""

import os
import threading
from pathlib import Path

import pytest

from nutricare_data_packages.storage_base import StorageBase


class ConcreteStorage(StorageBase):
    """用于测试的具象存储实现。"""

    @property
    def storage_subdir(self) -> str:
        return "test_subdir"

    def _write_impl(self, relative_path: str, data: bytes) -> Path:
        p = self._resolve(relative_path)
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_bytes(data)
        return p


class TestStorageBaseWrite:
    """先写元数据到真实表，再上传文件。"""

    @pytest.fixture
    def mongodb_url(self):
        return os.environ.get("MONGODB_URL", "mongodb://192.168.10.56:27017")

    def test_write_metadata_then_upload_file(self, mongodb_url):
        """先写元数据到真实表，再上传文件并校验。"""
        relative_path = "ceshi"
        content = b"content"
        ticket_id = "test_ticket_001"
        task_id = "test_task_001"

        t = threading.current_thread()
        t.ticket_id = ticket_id
        t.task_id = task_id

        storage = ConcreteStorage(mongodb_url=mongodb_url)
        storage.write_metadata(
            relative_path=relative_path,
            size=len(content),
            status="pending",
        )
        path = storage.write(relative_path, content)

        assert path.exists(), f"文件应写入: {path}"
        assert path.read_bytes() == content
        # 确认落在配置的存储根下
        assert path.resolve().relative_to(storage.get_root())
        doc = storage.metadata_collection.find_one(
            {"storage_subdir": "test_subdir", "relative_path": relative_path}
        )
        assert doc is not None
        assert doc.get("ticket_id") == ticket_id
        assert doc.get("task_id") == task_id
        assert doc.get("size") == len(content)
