from fastapi import APIRouter, Depends, HTTPException, Query, Path
from sqlmodel import Session, select
from sqlalchemy.exc import IntegrityError
from typing import List
import datetime as dt


from app.src.common.security import get_current_user
from app.src.common.utils import profiling_api
from app.src.models.app_user import AppUser
from app.src.models.product_type import (
    ProductType,
    ProductTypeRead,
    ProductTypeCreate,
    ProductTypeUpdate,
)
from app.src.db.engine import get_session

router = APIRouter()


# A scopo didattico inserita la validazione di producttype_id con Path:
# - non potrà essere < 1
async def get_producttype_or_404(
    *,
    session: Session = Depends(get_session),
    producttype_id: int = Path(..., ge=1),
    current_user: AppUser = Depends(get_current_user),
):
    start_time = dt.datetime.now()
    try:
        db_pt = session.get(ProductType, producttype_id)
        if db_pt:
            return {
                "db_pt": db_pt,
                "username": current_user.username,
                "start_time": start_time,
            }
        else:
            raise HTTPException(status_code=404, detail="Product type not found")
    except KeyError:
        raise HTTPException(status_code=400, detail="Product type not found")


@router.get("/", response_model=List[ProductTypeRead])
# lte -> less than or equal
async def read_product_types(
    *,
    session: Session = Depends(get_session),
    offset: int = 0,
    limit: int = Query(default=100, lte=100),
    current_user: AppUser = Depends(get_current_user),
):
    """
    Get all the existing product types
    """
    start_time = dt.datetime.now()
    product_types = session.exec(