"""Tests for DuckDB schema creation and management."""

from dyfinance._cache import CacheEngine
from dyfinance._schema import SCHEMA_VERSION


class TestSchemaCreation:
    def test_creates_all_tables(self, tmp_path):
        db_path = tmp_path / "schema_test.duckdb"
        engine = CacheEngine(db_path)

        tables = engine._con.execute(
            "SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
        ).fetchall()
        table_names = {row[0] for row in tables}

        assert "ohlcv" in table_names
        assert "cache_meta" in table_names
        assert "schema_version" in table_names

        engine.close()

    def test_ohlcv_table_columns(self, tmp_path):
        db_path = tmp_path / "schema_cols.duckdb"
        engine = CacheEngine(db_path)

        cols = engine._con.execute(
            "SELECT column_name FROM information_schema.columns "
            "WHERE table_name = 'ohlcv' ORDER BY ordinal_position"
        ).fetchall()
        col_names = [row[0] for row in cols]

        expected = [
            "ticker", "interval", "ts", "open", "high", "low", "close",
            "adj_close", "volume", "dividends", "stock_splits", "capital_gains",
        ]
        assert col_names == expected

        engine.close()

    def test_cache_meta_table_columns(self, tmp_path):
        db_path = tmp_path / "schema_meta.duckdb"
        engine = CacheEngine(db_path)

        cols = engine._con.execute(
            "SELECT column_name FROM information_schema.columns "
            "WHERE table_name = 'cache_meta' ORDER BY ordinal_position"
        ).fetchall()
        col_names = [row[0] for row in cols]

        expected = ["ticker", "interval", "cached_from", "cached_to", "fetched_at"]
        assert col_names == expected

        engine.close()

    def test_schema_idempotent(self, tmp_path):
        """Calling _init_schema twice should not raise."""
        db_path = tmp_path / "schema_idem.duckdb"
        engine = CacheEngine(db_path)
        engine._init_schema()  # Second call
        engine._init_schema()  # Third call

        count = engine._con.execute("SELECT COUNT(*) FROM schema_version").fetchone()[0]
        assert count == 1  # Only one version record

        engine.close()

    def test_schema_version_set(self, tmp_path):
        db_path = tmp_path / "schema_ver.duckdb"
        engine = CacheEngine(db_path)

        version = engine._con.execute("SELECT MAX(version) FROM schema_version").fetchone()[0]
        assert version == SCHEMA_VERSION

        engine.close()
