"""WhatsApp Business API (Meta Cloud) Blueprint.

Replaces Baileys webhook for scalable production messaging.
Stubs ready for Meta Cloud API credentials.
"""
from flask import Blueprint, request, jsonify, g
from functools import wraps
import uuid
from datetime import datetime

whatsapp_cloud_bp = Blueprint('whatsapp_cloud', __name__, url_prefix='/pos/api/whatsapp-cloud')


from middleware import require_auth


_mock_messages = {}


@whatsapp_cloud_bp.route('/webhook', methods=['GET', 'POST'])
def webhook():
    """Meta Cloud API webhook verification and message reception."""
    if request.method == 'GET':
        # Verification challenge
        mode = request.args.get('hub.mode')
        token = request.args.get('hub.verify_token')
        challenge = request.args.get('hub.challenge')
        # In production: verify token against configured VERIFY_TOKEN
        if mode == 'subscribe' and challenge:
            return challenge, 200
        return jsonify({'error': 'Verification failed'}), 403

    # POST — incoming messages
    data = request.get_json() or {}
    # In production: process entries, messages, statuses
    return jsonify({'received': True, 'entries': len(data.get('entry', []))}), 200


@whatsapp_cloud_bp.route('/messages', methods=['POST'])
@require_auth()
def send_message():
    """Send a message via Meta Cloud API."""
    data = request.get_json() or {}
    to = data.get('to')
    body = data.get('body')
    template = data.get('template')

    if not to or (not body and not template):
        return jsonify({'error': 'to and body/template are required'}), 400

    msg_id = str(uuid.uuid4())
    _mock_messages[msg_id] = {
        'id': msg_id,
        'to': to,
        'body': body,
        'template': template,
        'status': 'sent',
        'sent_at': datetime.utcnow().isoformat(),
    }
    return jsonify(_mock_messages[msg_id]), 201


@whatsapp_cloud_bp.route('/templates', methods=['GET'])
@require_auth()
def list_templates():
    """List approved message templates."""
    return jsonify({
        'templates': [
            {'name': 'order_ready', 'language': 'es_MX', 'category': 'UTILITY', 'status': 'APPROVED'},
            {'name': 'payment_reminder', 'language': 'es_MX', 'category': 'UTILITY', 'status': 'APPROVED'},
            {'name': 'welcome_message', 'language': 'es_MX', 'category': 'MARKETING', 'status': 'PENDING'},
        ]
    })


@whatsapp_cloud_bp.route('/status', methods=['GET'])
@require_auth()
def get_status():
    """Check Meta Cloud API connection status."""
    return jsonify({
        'connected': False,
        'phone_number_id': None,
        'business_account_id': None,
        'message_limit': None,
        'note': 'Configure WHATSAPP_CLOUD_ACCESS_TOKEN and PHONE_NUMBER_ID to connect',
    })
