import requests
import logging
from django.conf import settings
from .models import WhatsAppConfig

logger = logging.getLogger(__name__)

def send_whatsapp_message(phone, message):
    """
    Sends a WhatsApp message using the Wablas API.
    """
    try:
        config = WhatsAppConfig.objects.filter(is_active=True).first()
    except Exception as e:
        logger.error(f"Error fetching WhatsApp configuration: {e}")
        config = None

    if not config or not config.api_token:
        # Fallback to settings for backward compatibility or if DB entry is missing
        token = getattr(settings, 'WABLAS_API_TOKEN', None)
        secret_key = getattr(settings, 'WABLAS_SECRET_KEY', None)
    else:
        token = config.api_token
        secret_key = config.secret_key
    
    if not token:
        logger.warning("Wablas API credentials not configured.")
        return False

    url = "https://deu.wablas.com/api/send-message"
    
    # Headers logic based on whether secret key exists
    auth_header = token
    if secret_key:
        auth_header = f"{token}.{secret_key}"

    headers = {
        "Authorization": auth_header,
        "Content-Type": "application/x-www-form-urlencoded"
    }
    
    # Normalize phone number
    phone = str(phone).replace('+', '').replace(' ', '')

    data = {
        "phone": phone,
        "message": message,
    }

    try:
        response = requests.post(url, headers=headers, data=data, timeout=10)
        response_json = response.json()
        
        if response.status_code == 200 and response_json.get('status') == True:
            logger.info(f"WhatsApp message sent to {phone}")
            return True
        else:
            logger.error(f"Failed to send WhatsApp message to {phone}: {response.text}")
            return False
    except Exception as e:
        logger.exception(f"Exception while sending WhatsApp message: {str(e)}")
        return False