from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
import logging
from django.conf import settings
from .webhook_handlers import verify_webhook_token, parse_webhook_payload, handle_comment_event, handle_share_event

# Configure logging
logger = logging.getLogger(__name__)

VERIFY_TOKEN = settings.VERIFY_TOKEN

@csrf_exempt
def facebook_webhook(request):
    """
    Handles incoming webhook requests from Facebook.
    """
    if request.method == "POST":
        try:
            logger.info("Received POST request.")
            payload = json.loads(request.body)
            data = parse_webhook_payload(payload)

            sender_id = data.get("from", {}).get("id")
            page_id = payload.get("entry", [{}])[0].get("id")
            item_type = data.get("item")

            if item_type == "share":
                return handle_share_event(page_id, data)
            elif item_type == "comment":
                return handle_comment_event(page_id, sender_id, data)

        except json.JSONDecodeError as e:
            logger.error(f"JSON decoding error: {e}")
            return JsonResponse({"error": "Invalid JSON payload"}, status=400)
        except Exception as e:
            logger.error(f"Error processing webhook: {e}")
            return JsonResponse({"error": str(e)}, status=500)

        logger.info("POST request processed successfully.")
        return JsonResponse({"status": "success"}, status=200)

    logger.warning(f"Received unsupported HTTP method: {request.method}")
    return HttpResponse("Method Not Allowed", status=405)
