from decimal import Decimal
from typing import Optional
from .models import ExchangeRate

def get_exchange_rate(date) -> Optional[Decimal]:
    """Get exchange rate for a specific date"""
    try:
        exchange = ExchangeRate.objects.filter(
            date__lte=date
        ).order_by('-date').first()
        return exchange.rate if exchange else None
    except Exception:
        return None


def convert_currency(amount: Decimal, from_currency: str, to_currency: str, date) -> Optional[Decimal]:
    """Convert between currencies using exchange rate"""
    if from_currency == to_currency:
        return amount

    rate = get_exchange_rate(date)
    if not rate:
        return None

    if from_currency == 'dollar' and to_currency == 'dinar':
        return amount * rate
    elif from_currency == 'dinar' and to_currency == 'dollar':
        return amount / rate

    return None