"""Unit tests for SQLAlchemyAssetRepository - storage_key field coverage."""

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "apps" / "api"))

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from packages.adapters.sqlalchemy_impl.asset_repository import SQLAlchemyAssetRepository
from packages.adapters.sqlalchemy_impl.models import Base
from packages.domain import Asset, AssetStatus


def _repository():
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    session = sessionmaker(bind=engine)()
    return SQLAlchemyAssetRepository(session)


def test_asset_repository_create_preserves_storage_key():
    """create时storage_key字段正确写入数据库。"""
    repository = _repository()
    asset = Asset.create(
        project_id="proj-1",
        library_id="lib-1",
        name="test_video.mp4",
        storage_key="assets/proj-1/test_video.mp4",
        mime_type="video/mp4",
        file_size=102400,
    )

    repository.create(asset)
    saved = repository.get(asset.id)

    assert saved is not None
    assert saved.storage_key == "assets/proj-1/test_video.mp4"


def test_asset_repository_update_preserves_storage_key():
    """update时storage_key字段正确更新。"""
    repository = _repository()
    asset = Asset.create(
        project_id="proj-1",
        library_id="lib-1",
        name="test_video.mp4",
        storage_key="assets/proj-1/old_key.mp4",
        mime_type="video/mp4",
    )
    repository.create(asset)

    # 更新storage_key
    asset.storage_key = "assets/proj-1/new_key.mp4"
    repository.update(asset)

    saved = repository.get(asset.id)
    assert saved.storage_key == "assets/proj-1/new_key.mp4"


def test_asset_repository_to_domain_fallback_to_file_url():
    """_to_domain中storage_key为空时fallback到file_url（兼容存量数据）。"""
    from sqlalchemy.orm import sessionmaker

    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    session = sessionmaker(bind=engine)()
    repository = SQLAlchemyAssetRepository(session)

    # 直接插入一条storage_key为空的记录（模拟存量数据）
    from packages.adapters.sqlalchemy_impl.models import AssetModel

    model = AssetModel(
        id="asset-legacy-001",
        project_id="proj-1",
        asset_library_id="lib-1",
        name="legacy_asset.mp4",
        file_type="video",
        file_size=204800,
        file_url="legacy/storage/key.mp4",  # 老数据file_url存的是storage_key
        storage_key="",  # 新字段为空
        status="ready",
        classification_status="pending",
        uploaded_by_user_id="user-1",
    )
    session.add(model)
    session.commit()

    saved = repository.get("asset-legacy-001")
    assert saved is not None
    assert saved.storage_key == "legacy/storage/key.mp4"  # fallback到file_url
