
from flask import Blueprint, request, jsonify
from utils import require_api_key, format_api_response, create_error_response
from services.notification_service import onesignal_service
import logging

logger = logging.getLogger(__name__)
notification_bp = Blueprint('notification', __name__)

@notification_bp.route('/api/notifications/send', methods=['POST'])
@require_api_key
def send_notification():
    """
    Send a push notification to specific users or segments.
    Payload:
    {
        "user_ids": ["1", "2"],  # Optional (list of user IDs)
        "segment": "All",        # Optional (default if user_ids not provided)
        "title": "Hello",
        "message": "Welcome!",
        "data": {"type": "course", "id": "123"}
    }
    """
    try:
        data = request.get_json()
        if not data:
            return create_error_response("Request body is empty", 400)
            
        title = data.get('title')
        message = data.get('message')
        
        if not title or not message:
            return create_error_response("Title and message are required", 400)
            
        user_ids = data.get('user_ids')
        segment = data.get('segment')
        custom_data = data.get('data')

        result = {}
        
        # Priority: User IDs > Segment
        if user_ids and isinstance(user_ids, list) and len(user_ids) > 0:
            result = onesignal_service.send_notification_to_users(
                user_ids, title, message, custom_data
            )
        elif segment:
            result = onesignal_service.send_notification_to_segment(
                segment, title, message, custom_data
            )
        else:
            # Default to "All" users if nothing specified is risky, so we require explicit segment
            # But for convenience, let's default to "Subscribed Users" if purely testing
            return create_error_response("Must provide 'user_ids' list or 'segment' name", 400)

        if result.get('success'):
            return jsonify(format_api_response(
                data=result,
                message="Notification sent successfully"
            )), 200
        else:
            return create_error_response(
                f"Failed to send notification: {result.get('error')}", 
                500
            )

    except Exception as e:
        logger.error(f"Error in send_notification route: {str(e)}")
        return create_error_response(str(e), 500)
