import asyncio
import os
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text
from dotenv import load_dotenv

load_dotenv()

# DB Config
raw_url = os.getenv("DATABASE_URL")
if not raw_url:
    raw_url = "postgresql://admin:PASSWORD_111@postgres-db:5432/service_finder"
DATABASE_URL = raw_url.replace("postgresql://", "postgresql+asyncpg://").replace("/service_finder_db", "/service_finder")

async def check_data():
    engine = create_async_engine(DATABASE_URL)
    async with engine.begin() as conn:
        print("\n🚗 A TE GARÁZSOD (User ID: 1):")
        print("-" * 80)
        
        # Ez a lekérdezés összeköti a Történelmet (History), a Vasat (Vehicle) és a Katalógust (Model)
        query = text("""
            SELECT 
                vh.role,
                vh.start_date,
                v.vin,
                v.current_plate,
                m.name as brand,
                mo.model_name
            FROM data.vehicle_history vh
            JOIN data.vehicles v ON vh.vehicle_id = v.id
            JOIN ref.vehicle_models mo ON v.model_id = mo.id
            JOIN ref.vehicle_makes m ON mo.make_id = m.id
            WHERE vh.user_id = 1;
        """)
        
        result = await conn.execute(query)
        rows = result.fetchall()
        
        if not rows:
            print("📭 A garázs üres.")
        else:
            for r in rows:
                print(f"🔹 {r.brand} {r.model_name} | 🆔 {r.vin} | 🔢 {r.current_plate}")
                print(f"   Jogviszony: {r.role} | Kezdete: {r.start_date}")
                print("-" * 80)

    await engine.dispose()

if __name__ == "__main__":
    asyncio.run(check_data())
