"""Push notification subscription routes."""
import logging

from quart import Blueprint, jsonify, request

from fabledassistant.auth import login_required, get_current_user_id, admin_required
from fabledassistant.config import Config
from fabledassistant.services.push import delete_subscription, regenerate_vapid_keys, save_subscription, vapid_enabled

logger = logging.getLogger(__name__)

push_bp = Blueprint("push", __name__, url_prefix="/api/push")


@push_bp.route("/vapid-public-key", methods=["GET"])
@login_required
async def get_vapid_key():
    if not vapid_enabled():
        return jsonify({"error": "Push notifications not configured"}), 503
    return jsonify({"publicKey": Config.VAPID_PUBLIC_KEY})


@push_bp.route("/subscribe", methods=["POST"])
@login_required
async def subscribe():
    uid = get_current_user_id()
    data = await request.get_json()
    if not data or not data.get("endpoint"):
        return jsonify({"error": "Invalid subscription data"}), 400
    user_agent = request.headers.get("User-Agent")
    sub = await save_subscription(uid, data, user_agent=user_agent)
    return jsonify({"id": sub.id}), 201


@push_bp.route("/subscribe", methods=["DELETE"])
@login_required
async def unsubscribe():
    uid = get_current_user_id()
    data = await request.get_json()
    endpoint = (data or {}).get("endpoint", "")
    if not endpoint:
        return jsonify({"error": "endpoint is required"}), 400
    await delete_subscription(uid, endpoint)
    return "", 204


@push_bp.route("/reset-vapid", methods=["POST"])
@admin_required
async def reset_vapid():
    """Regenerate VAPID keys and clear all push subscriptions."""
    ok = await regenerate_vapid_keys()
    if ok:
        return jsonify({"publicKey": Config.VAPID_PUBLIC_KEY}), 200
    return jsonify({"error": "Key regeneration failed"}), 500
