import unittest
import os
import tempfile
from feather.database.db import DatabaseManager


class TestDatabaseManager(unittest.TestCase):
    def setUp(self):
        self.temp_db = tempfile.NamedTemporaryFile(delete=False, suffix='.db')
        self.db = DatabaseManager(f'sqlite:///{self.temp_db.name}')
    
    def tearDown(self):
        os.unlink(self.temp_db.name)
    
    def test_save_and_query(self):
        result_id = self.db.save('users', {'name': 'John Doe', 'email': 'john@example.com'})
        self.assertIsNotNone(result_id)
        
        users = self.db.query('users')
        self.assertEqual(len(users), 1)
        self.assertEqual(users[0].name, 'John Doe')
        self.assertEqual(users[0].email, 'john@example.com')
    
    def test_identifier_validation(self):
        with self.assertRaises(ValueError):
            self.db.save('users; DROP TABLE users;', {'name': 'Hacker'})
        
        with self.assertRaises(ValueError):
            self.db.save('users', {'name; DROP TABLE users;': 'Hacker'})
        
        with self.assertRaises(ValueError):
            self.db.save('SELECT', {'name': 'Test'})
    
    def test_update(self):
        result_id = self.db.save('users', {'name': 'Jane Doe'})
        self.db.update('users', result_id, {'name': 'Jane Smith'})
        
        users = self.db.query('users', where={'id': result_id})
        self.assertEqual(users[0].name, 'Jane Smith')
    
    def test_delete(self):
        result_id = self.db.save('users', {'name': 'To Delete'})
        self.db.delete('users', result_id)
        
        users = self.db.query('users')
        self.assertEqual(len(users), 0)
    
    def test_query_with_filters(self):
        self.db.save('users', {'name': 'Alice', 'age': 25})
        self.db.save('users', {'name': 'Bob', 'age': 30})
        self.db.save('users', {'name': 'Charlie', 'age': 25})
        
        users_25 = self.db.query('users', where={'age': 25})
        self.assertEqual(len(users_25), 2)
        
        limited = self.db.query('users', limit=2)
        self.assertEqual(len(limited), 2)


if __name__ == '__main__':
    unittest.main()
