from quart import Blueprint, jsonify, request

from scribe.auth import login_required, get_current_user_id
from scribe.services.api_keys import create_api_key, list_api_keys, revoke_api_key

api_keys_bp = Blueprint("api_keys", __name__, url_prefix="/api/api-keys")


@api_keys_bp.route("", methods=["GET"])
@login_required
async def list_keys_route():
    uid = get_current_user_id()
    keys = await list_api_keys(uid)
    return jsonify({"api_keys": keys})


@api_keys_bp.route("", methods=["POST"])
@login_required
async def create_key_route():
    uid = get_current_user_id()
    data = await request.get_json(force=True, silent=True) or {}
    name = (data.get("name") or "").strip()
    scope = (data.get("scope") or "").strip()

    if not name:
        return jsonify({"error": "name is required"}), 400
    if scope not in ("read", "write"):
        return jsonify({"error": "scope must be 'read' or 'write'"}), 400

    full_key, key_dict = await create_api_key(uid, name=name, scope=scope)
    # Return the full key ONCE — it is never retrievable again
    return jsonify({"key": full_key, "api_key": key_dict}), 201


@api_keys_bp.route("/<int:key_id>", methods=["DELETE"])
@login_required
async def revoke_key_route(key_id: int):
    uid = get_current_user_id()
    deleted = await revoke_api_key(uid, key_id)
    if not deleted:
        return jsonify({"error": "API key not found"}), 404
    return "", 204
