from logging import getLogger
from venv import logger
from fastapi.responses import JSONResponse
from config.messages import ErrorResponse, UserResponse
from datetime import datetime, timedelta, time
from services.data_service import DataServiceFactory
from fastapi import APIRouter, Depends
from models.sales import Sale
from utils.responses import error_response, success_response


sale_data_service = DataServiceFactory.get_sales_service()
user_data_service = DataServiceFactory.get_user_service()

logger = getLogger(__name__)
sales_router = APIRouter()

@sales_router.get("/user/{user_id}", response_model=list[Sale])
def get_user_sales(user_id: int):
    user = user_data_service.get_by_id(user_id)
    if not user:
        return error_response(UserResponse.USER_NOT_FOUND.format(user_id=user_id), status_code=404)
    sales = sale_data_service.get_by_user(user_id)
    
    # solo las ventas del dia, estilo 12pm a 3am del dia siguiente
    # suponiendo que today es la fecha de referencia
    start = datetime.combine(datetime.today(), time(12, 0))          # hoy a las 12:00 pm
    end = start + timedelta(hours=15)                     # mañana a las 3:00 am

    sales = [sale for sale in sales if start <= sale.date < end]
    
    if not sales:
        return error_response(ErrorResponse.SALE_NOT_FOUND, status_code=404)
    logger.info(f"Sales found for user {user_id}: {len(sales)} sales")
    return success_response(data=[{**sale.model_dump(), "date": sale.date.isoformat()} for sale in sales], message="Ventas obtenidas correctamente.")