"""Tests for column_metadata round-trip through BaselineData serialization."""

from __future__ import annotations

import json
import tempfile
from pathlib import Path

from test_runner.common.baseline import load_baseline, write_baseline
from test_runner.common.models import BaselineData


_SAMPLE_METADATA = {
    "WAREHOUSE.COLORS": {
        "platform_managed_columns": ["VALIDFROM", "VALIDTO"],
        "identity_columns": ["COLORID"],
    },
}


class TestColumnMetadataRoundTrip:
    def test_to_dict_includes_column_metadata(self):
        bl = BaselineData(
            procedure="dbo.InsertColor",
            parameters={"Color": "Blue"},
            captured_at="2026-01-01T00:00:00Z",
            result_sets=[],
            row_counts=[],
            success=True,
            column_metadata=_SAMPLE_METADATA,
        )

        d = bl.to_dict()
        assert "column_metadata" in d
        assert d["column_metadata"] == _SAMPLE_METADATA

    def test_to_dict_omits_when_empty(self):
        bl = BaselineData(
            procedure="dbo.GetColor",
            parameters={},
            captured_at="2026-01-01T00:00:00Z",
            result_sets=[],
            row_counts=[],
            success=True,
        )

        d = bl.to_dict()
        assert "column_metadata" not in d

    def test_write_and_load_preserves_metadata(self, tmp_path: Path):
        bl = BaselineData(
            procedure="dbo.InsertColor",
            parameters={"Color": "Blue"},
            captured_at="2026-01-01T00:00:00Z",
            result_sets=[],
            row_counts=[],
            success=True,
            column_metadata=_SAMPLE_METADATA,
        )

        path = write_baseline(bl, tmp_path, case_index=0)
        loaded = load_baseline(path)

        assert loaded is not None
        assert loaded.column_metadata == _SAMPLE_METADATA

    def test_load_without_metadata_field(self, tmp_path: Path):
        """Baselines captured before this feature have no column_metadata."""
        bl = BaselineData(
            procedure="dbo.GetColor",
            parameters={},
            captured_at="2026-01-01T00:00:00Z",
            result_sets=[],
            row_counts=[],
            success=True,
        )

        path = write_baseline(bl, tmp_path, case_index=0)
        loaded = load_baseline(path)

        assert loaded is not None
        assert loaded.column_metadata is None
