from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text
from app.api.deps import get_db, get_current_user
from typing import List, Dict, Optional
from app.models.vehicle import Vehicle

router = APIRouter()

@router.get("/search/brands")
async def search_brands(q: str = Query(..., min_length=2), db: AsyncSession = Depends(get_db)):
    query = text("""
        SELECT id, name, slug, country_of_origin 
        FROM data.vehicle_brands 
        WHERE (name ILIKE :q OR slug ILIKE :q) AND is_active = true 
        ORDER BY name ASC LIMIT 10
    """)
    # 1. Megvárjuk az execute-ot
    result = await db.execute(query, {"q": f"%{q}%"})
    # 2. Külön hívjuk a fetchall-t az eredményen
    rows = result.fetchall()
    
    brand_list = [dict(row._mapping) for row in rows]
    if not brand_list:
        return {"status": "discovery_mode", "data": []}
    return {"status": "success", "data": brand_list}

@router.get("/search/providers")
async def search_providers(q: str = Query(..., min_length=2), db: AsyncSession = Depends(get_db)):
    query = text("""
        SELECT id, name, technical_rating_pct, location_city, service_type
        FROM data.service_providers 
        WHERE (name ILIKE :q OR service_type ILIKE :q) AND is_active = true 
        ORDER BY technical_rating_pct DESC LIMIT 15
    """)
    result = await db.execute(query, {"q": f"%{q}%"})
    rows = result.fetchall()
    return {"status": "success", "data": [dict(row._mapping) for row in rows]}

@router.post("/register")
async def register_user_vehicle(data: dict, db: AsyncSession = Depends(get_db), current_user = Depends(get_current_user)):
    company_res = await db.execute(text("SELECT id FROM data.companies WHERE owner_id = :u LIMIT 1"), {"u": current_user.id})
    company = company_res.fetchone()
    if not company:
        raise HTTPException(status_code=404, detail="Széf nem található.")

    new_vehicle = Vehicle(
        current_company_id=company.id,
        brand_id=data.get("brand_id"),
        model_name=data.get("model_name"),
        engine_spec_id=data.get("engine_spec_id"),
        identification_number=data.get("vin"),
        license_plate=data.get("plate"),
        tracking_mode=data.get("tracking_mode", "km"),
        total_real_usage=data.get("current_odo", 0)
    )
    db.add(new_vehicle)
    await db.commit()
    return {"status": "success", "vehicle_id": str(new_vehicle.id)}