from fastapi import APIRouter, Depends, HTTPException, Query, Path
from sqlmodel import Session, select
from sqlalchemy.exc import IntegrityError
from typing import List, Any
import datetime as dt
from app.src.common.utils import profiling_api

from app.src.models.product import (
    Product,
    ProductRead,
    ProductCreate,
    ProductUpdate,
    ProductReadwithTypeAndTags,
)
from app.src.db.engine import get_session
from app.src.api.endpoints.product_type import get_producttype_or_404
from app.src.api.endpoints.tags import get_tag_or_404, get_tag_by_name_or_404
from app.src.common.security import get_current_user
from app.src.models.app_user import AppUser
from app.src.models.tag import Tag
from app.src.logger import logger


router = APIRouter()


async def get_product_or_404(
    *,
    session: Session = Depends(get_session),
    product_id: int = Path(..., ge=1),
    current_user: AppUser = Depends(get_current_user),
):
    start_time = dt.datetime.now()
    try:
        db_product = session.get(Product, product_id)
        if db_product:
            return {
                "db_product": db_product,
                "username": current_user.username,
                "start_time": start_time,
            }
        else:
            logger.error("Product not found")
            logger.exception("Product not found")
            raise HTTPException(status_code=404, detail="Product not found")
    except KeyError:
        logger.error("Product not found")
        logger.exception("KeyError: Product not found")
        raise HTTPException(status_code=400, detail="Product not found")


@router.get("/", response_model=List[ProductReadwithTypeAndTags])
async def read_all_products(
    session: Session = Depends(get_session),
    offset: int = 0,
    limit: int = Query(default=100, lte=100),
    current_user: AppUser = Depends(get_current_user),
) -> Any:
    """
    Retrieve all products
    """
    start_time = dt.datetime.now()
    products = session.exec(