"""Unit tests for the database module."""

from __future__ import annotations

from pathlib import Path

from core.database import Database


class TestDatabase:
    """Tests for Database class."""

    def test_creates_db_file(self, tmp_path: Path) -> None:
        db_path = tmp_path / "test.db"
        db = Database(db_path)
        assert db_path.exists()
        db.close()

    def test_creates_parent_dirs(self, tmp_path: Path) -> None:
        db_path = tmp_path / "sub" / "dir" / "test.db"
        db = Database(db_path)
        assert db_path.exists()
        db.close()

    def test_schema_creates_tables(self, tmp_path: Path) -> None:
        db = Database(tmp_path / "test.db")
        tables = db.conn.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").fetchall()
        table_names = [row["name"] for row in tables]
        assert "sessions" in table_names
        assert "memories" in table_names
        assert "system_prompts" in table_names
        db.close()

    def test_wal_mode_enabled(self, tmp_path: Path) -> None:
        db = Database(tmp_path / "test.db")
        mode = db.conn.execute("PRAGMA journal_mode").fetchone()
        assert mode[0] == "wal"
        db.close()

    def test_reentrant_init(self, tmp_path: Path) -> None:
        """Opening the same DB twice should not fail (CREATE IF NOT EXISTS)."""
        db_path = tmp_path / "test.db"
        db1 = Database(db_path)
        db1.close()
        db2 = Database(db_path)
        # Should still have all tables
        tables = db2.conn.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").fetchall()
        assert len([r for r in tables if r["name"] in ("sessions", "memories", "system_prompts")]) == 3
        db2.close()
