from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.database import get_db
from app.schemas.user.order_schemas import (
    VoucherValidationRequest,
    VoucherValidationResponse,
)
from app.services.user.voucher_service import VoucherService
from app.utils.auth import get_customer_user


router = APIRouter()


@router.post(
    "/vouchers/validate",
    response_model=VoucherValidationResponse,
    status_code=status.HTTP_200_OK,
    summary="Validate a voucher for a user order",
)
async def validate_voucher(
    payload: VoucherValidationRequest,
    current_user: dict = Depends(get_customer_user),
    db: AsyncSession = Depends(get_db),
):
    from fastapi import HTTPException
    
    service = VoucherService(db)
    
    # Get voucher without full validation first
    voucher = await service.get_voucher_by_code(payload.code)
    
    if not voucher:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Voucher not found"
        )
    
    # Check if voucher is actually valid (DB active flag AND not expired)
    # Use the static method directly to check expiration
    is_valid_today = VoucherService._is_voucher_valid_today(voucher)
    
    # If voucher is not active in DB, return error
    if not voucher.is_active:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Voucher code is not active"
        )
    
    # If voucher is expired, return error
    if not is_valid_today:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Voucher code is expired or not yet valid"
        )
    
    # If voucher is valid, perform full validation and calculate discount
    try:
        voucher, discount_amount = await service.validate_and_calculate_discount(
            payload.code,
            payload.order_total,
        )
        final_amount = max(payload.order_total - discount_amount, 0.0)
        
        return VoucherValidationResponse(
            code=voucher.code,
            description=voucher.description,
            discount_type=voucher.discount_type,
            discount_value=voucher.discount_value,
            discount_amount=discount_amount,
            final_amount=final_amount,
            max_uses=voucher.max_uses,
            used_count=voucher.used_count,
            min_order_amount=voucher.min_order_amount,
            valid_from=voucher.valid_from,
            valid_to=voucher.valid_to,
            is_active=True,  # Only true if it passed all validations
        )
    except HTTPException:
        # If validation fails for other reasons (usage limit, min amount), re-raise
        raise

