import time
from typing import List

import oracledb
from fastapi import APIRouter, Depends, HTTPException

from shared.auth.dependencies import get_current_user
from shared.auth.models import CurrentUser
from shared.database.oracle_pool import oracle_pool

from ..schemas.comanda import (
    ComandaRequest, ComandaResponse,
    FirmaItem, TipDevizItem, MasinaClientItem,
)
from ..services.comanda_service import ComandaService
from ..services.lookup_service import LookupService

router = APIRouter()


@router.get("/ping")
async def ping(_: CurrentUser = Depends(get_current_user)):
    """Health check: verifies Oracle connectivity for mariusm_test server."""
    t0 = time.perf_counter()
    try:
        async with oracle_pool.get_connection('mariusm_test') as conn:
            with conn.cursor() as cursor:
                cursor.execute('SELECT 1 FROM DUAL')
                row = cursor.fetchone()
    except oracledb.DatabaseError as e:
        raise HTTPException(status_code=503, detail=f"Oracle error: {e}")
    elapsed_ms = round((time.perf_counter() - t0) * 1000, 2)
    return {"result": row[0], "server": "mariusm_test", "latency_ms": elapsed_ms}


@router.get("/firme", response_model=List[FirmaItem])
async def get_firme(current_user: CurrentUser = Depends(get_current_user)):
    """Firmele accesibile utilizatorului curent (din JWT companies[])."""
    return await LookupService.get_firme(current_user.companies)


@router.get("/tip-deviz", response_model=List[TipDevizItem])
async def get_tip_deviz(_: CurrentUser = Depends(get_current_user)):
    """Tipuri de deviz din DEV_TIP_DEVIZ."""
    return await LookupService.get_tip_deviz()


@router.get("/masini", response_model=List[MasinaClientItem])
async def get_masini(_: CurrentUser = Depends(get_current_user)):
    """Mașini active din AUTO_VMASINICLIENTI (toate firmele pe același server)."""
    return await LookupService.get_masini()


@router.post("/comenzi", response_model=ComandaResponse)
async def creeaza_comanda(
    data: ComandaRequest,
    current_user: CurrentUser = Depends(get_current_user),
):
    try:
        return await ComandaService.creeaza_comanda(
            data=data,
            username=current_user.username,
        )
    except NotImplementedError as e:
        raise HTTPException(status_code=501, detail=str(e))
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
