from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse
from typing import Optional
from datetime import datetime

from app.db import database
from app.v1.dependencies.auth import get_current_userdetails
from app.v1.models.platform.vehiclesmodel import (
    Vehicle,
    VehicleBase,
    VehicleCreate,
    VehicleResponseList,
    VehicleUpdate
)
from app.v1.services.platform.vehicles import (
    create_vehicle_service,
    get_vehicles_service,
    read_vehicle_service,
    update_vehicle_service,
    delete_vehicle_service
)

router = APIRouter()

@router.post("/", response_model=Vehicle)
def create_vehicle_endpoint(
    vehicle: VehicleBase,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    # Create the vehicle data with user info
    current_time = datetime.utcnow()
    vehicle_dict = vehicle.model_dump()
    
    # Handle optional fields - convert None to 0 or keep as None based on your preference
    if vehicle_dict.get('max_speed') is None:
        vehicle_dict['max_speed'] = 0  # or None if you prefer to store as null
    if vehicle_dict.get('engine_capacity') is None:
        vehicle_dict['engine_capacity'] = 0  # or None if you prefer to store as null
    
    vehicle_data = {
        **vehicle_dict,
        "account_id": current_user.get("account_id", ""),
        "user_id": current_user.get("user_id", ""),
        "created_date": current_time,
        "updated_date": current_time
    }
    
    result = create_vehicle_service(vehicle_data, db)
    return JSONResponse(
        content={"message": "Vehicle created successfully", "vehicle": result["vehicle_data"]}
    )

@router.get("/list/{account_id}/", response_model=VehicleResponseList)
def get_vehicles(
    account_id: str,
    skip: int = 0,
    limit: int = 10,
    status: Optional[str] = None,
    created_date_from: Optional[str] = None,
    created_date_to: Optional[str] = None,
    q: Optional[str] = None,
    sort_by: Optional[str] = None,               
    sort_order: Optional[str] = "asc",           
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    if account_id != "all" and account_id != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return get_vehicles_service(account_id, skip, limit, status, created_date_from, created_date_to, q, sort_by, sort_order, db)

@router.get("/{vehicle_id}", response_model=Vehicle)
def read_vehicle(
    vehicle_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    vehicle = read_vehicle_service(vehicle_id, db)
    
    if vehicle.get("account_id") and vehicle["account_id"] != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return vehicle

@router.put("/{vehicle_id}", response_model=Vehicle)
def update_vehicle(
    vehicle_id: str,
    vehicle_data: VehicleUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    existing_vehicle = read_vehicle_service(vehicle_id, db)
    
    if existing_vehicle.get("account_id") and existing_vehicle["account_id"] != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return update_vehicle_service(vehicle_id, vehicle_data, db)

@router.delete("/{vehicle_id}", response_model=Vehicle)
def delete_vehicle(
    vehicle_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    existing_vehicle = read_vehicle_service(vehicle_id, db)
    
    if existing_vehicle.get("account_id") and existing_vehicle["account_id"] != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return delete_vehicle_service(vehicle_id, db)