from datetime import datetime, timezone
from sqlalchemy.orm import Session
from fastapi import HTTPException, status

from src.utils.pagination import QueryPaginator
from src.apps.base.models.country import Country
from uuid import UUID
from sqlalchemy.exc import IntegrityError
from typing import Optional
from src.apps.wine.wine.models.wine import WineDb
from src.apps.wine.retailer.models.retailer import RetailerWine
from src.core.exceptions import APIException
from src.apps.wine.retailer.schemas.retailer_wine import RetailerOutputSchema,RetailerWineCreateSchema,RetailerWineUpdateSchema
from src.utils.constants import API_PREFIXES
from src.core.config import settings
from typing import List


async def get_retailer_wines_by_wine_id(
    db: Session,
    wine_id: int
) -> any:
    try:
        retailer_wines = db.query(RetailerWine).filter(
            RetailerWine.wine_id == wine_id,
            RetailerWine.deleted_at.is_(None)
        ).all()
        return [rw for rw in retailer_wines]
    except Exception as e:
        raise APIException(
            module="get_retailer_wines_by_wine_id",
            error={"exception": str(e)},
            status_code=status.HTTP_400_BAD_REQUEST,
            message="Error fetching retailer wines."
        )
        
        
async def create_retailer_wine(
    db: Session,
    payload: RetailerWineCreateSchema
) -> RetailerOutputSchema:
    try:
        retailer_wine = RetailerWine(**payload.model_dump())
        db.add(retailer_wine)
        db.commit()
        db.refresh(retailer_wine)
        return RetailerOutputSchema.model_validate(retailer_wine)
    except Exception as e:
        db.rollback()
        raise APIException(
            module="create_retailer_wine",
            error={"exception": str(e)},
            status_code=status.HTTP_400_BAD_REQUEST,
            message="Error creating retailer wine."
        )
        
async def find_retailer_wine_by_sku_and_bottle_size(
    db: Session,
    retailer_id: int,
    wine_id: int,
    sku: str,
    bottle_size_id: int
) -> any:
   try:
       retailer_wine = db.query(RetailerWine).filter(
           RetailerWine.retailer_id == retailer_id,
           RetailerWine.wine_id == wine_id,
           RetailerWine.sku == sku,
           RetailerWine.bottle_size_id == bottle_size_id,
           RetailerWine.deleted_at.is_(None)
       ).first()
       return retailer_wine
   except Exception as e:
       raise APIException(
           module="find_retailer_wine_by_wine_sku_bottle_size",
           error={"exception": str(e)},
           status_code=status.HTTP_400_BAD_REQUEST,
           message="Error finding retailer wine."
       )