"""
Database helper for tests - provides fixtures for creating test data
"""

import uuid
import pytest
import sys
import os

# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))


class DBHelper:
    """Helper class for creating test data in the database."""
    
    def __init__(self):
        import core.postgres as postgres
        self.postgres = postgres
    
    def create_user(self, data=None):
        """Create a test user."""
        if data is None:
            data = {}
        user = {
            "id": data.get("id", str(uuid.uuid4())),
            "username": data.get("username", f"testuser_{uuid.uuid4().hex[:8]}"),
            "password_hashed": data.get("password_hashed", "$2b$12$test"),
        }
        return self.postgres.insert("users", user)
    
    def create_routine(self, data):
        """Create a test routine."""
        return self.postgres.insert("routines", data)
    
    def create_step(self, data):
        """Create a test routine step."""
        return self.postgres.insert("routine_steps", data)
    
    def create_session(self, data):
        """Create a test routine session."""
        return self.postgres.insert("routine_sessions", data)
    
    def create_tag(self, data):
        """Create a test tag."""
        return self.postgres.insert("routine_tags", data)
    
    def create_template(self, data):
        """Create a test template."""
        return self.postgres.insert("routine_templates", data)
    
    def create_template_step(self, data):
        """Create a test template step."""
        return self.postgres.insert("routine_template_steps", data)
    
    def create_streak(self, data):
        """Create a test streak."""
        return self.postgres.insert("routine_streaks", data)
    
    def cleanup(self, user_uuid):
        """Clean up test data for a user."""
        # Delete in reverse order of dependencies
        self.postgres.delete("routine_streaks", {"user_uuid": user_uuid})
        self.postgres.delete("routine_session_notes", {})
        self.postgres.delete("routine_sessions", {"user_uuid": user_uuid})
        self.postgres.delete("routine_steps", {})
        self.postgres.delete("routine_routine_tags", {})
        self.postgres.delete("routine_schedules", {})
        self.postgres.delete("routine_template_steps", {})
        self.postgres.delete("routine_templates", {})
        self.postgres.delete("routines", {"user_uuid": user_uuid})
        self.postgres.delete("users", {"id": user_uuid})


@pytest.fixture
def db_helper():
    """Fixture that provides a DBHelper instance."""
    return DBHelper()
