"""Demo provisioning blueprint."""
from flask import Blueprint, request, jsonify
from blueprints.auth_bp import require_manager_auth
from services import tenant_service

demos_bp = Blueprint("demos", __name__, url_prefix="/api/demos")


@demos_bp.route("", methods=["POST"])
@require_manager_auth
def create_demo():
    data = request.get_json() or {}
    name = data.get("name", "").strip()
    email = data.get("email", "").strip()
    days = data.get("days")
    subdomain = data.get("subdomain", "").strip() or None
    pin = data.get("pin", "0000").strip()

    if not name:
        return jsonify({"error": "Business name is required"}), 400

    try:
        result = tenant_service.create_demo(
            name=name,
            email=email,
            demo_days=days,
            subdomain=subdomain,
            pin=pin
        )
        return jsonify({"data": result}), 201
    except ValueError as e:
        return jsonify({"error": str(e)}), 409
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@demos_bp.route("", methods=["GET"])
@require_manager_auth
def list_demos():
    all_tenants = tenant_service.list_tenants(include_stats=True)
    demos = [t for t in all_tenants if t.get("is_demo")]
    return jsonify({"data": demos})
