import logging
from unittest.mock import MagicMock, patch

import pytest

from database import MotionDatabase


class TestMotionDatabaseExceptionHandling:
    @patch("database.duckdb")
    def test_init_database_catches_duckdb_connect_errors(self, mock_duckdb, tmp_path):
        mock_duckdb.Error = Exception
        mock_duckdb.connect.side_effect = mock_duckdb.Error("db locked")
        db = MotionDatabase(db_path=str(tmp_path / "test.db"))
        assert db._file_mode is True

    @patch("database.duckdb")
    def test_insert_motion_catches_errors_and_returns_false(self, mock_duckdb, tmp_path):
        mock_duckdb.Error = Exception
        mock_conn = MagicMock()
        mock_duckdb.connect.return_value = mock_conn

        db = MotionDatabase(db_path=str(tmp_path / "test.db"))
        # Now make insert_motion fail
        mock_conn.execute.side_effect = mock_duckdb.Error("constraint violation")
        result = db.insert_motion({"title": "Test", "date": "2024-01-01", "url": "http://test"})
        assert result is False

    @patch("database.duckdb")
    def test_query_motions_catches_errors_and_returns_empty_list(self, mock_duckdb, tmp_path):
        mock_duckdb.Error = Exception
        mock_conn = MagicMock()
        mock_duckdb.connect.return_value = mock_conn

        db = MotionDatabase(db_path=str(tmp_path / "test.db"))
        mock_conn.execute.side_effect = mock_duckdb.Error("syntax error")
        result = db.get_filtered_motions()
        assert result == []
