from flask import Blueprint, flash, jsonify, redirect, render_template, request, session, url_for

from app.models import generate_referral_code, get_referral_stats
from app.routes.auth import current_user, login_required

referral_bp = Blueprint("referral", __name__, url_prefix="/referral")


@referral_bp.route("/")
@login_required
def referral_page():
    """Referral dashboard — view code, stats, share link."""
    user = current_user()
    if not user:
        return redirect(url_for("auth.login"))

    user_id = session["user_id"]
    code = generate_referral_code(user_id)  # generates if not exists
    stats = get_referral_stats(user_id)

    # Build share URL
    base_url = request.host_url.rstrip("/")
    share_url = f"{base_url}/auth/register?ref={code}"

    return render_template(
        "referral.html",
        user=user,
        code=code,
        stats=stats,
        share_url=share_url,
    )


@referral_bp.route("/stats", methods=["GET"])
@login_required
def referral_stats():
    """JSON endpoint for referral stats."""
    user = current_user()
    if not user:
        return jsonify({"error": "not authenticated"}), 401

    stats = get_referral_stats(session["user_id"])
    return jsonify(stats)


@referral_bp.route("/copy-code", methods=["POST"])
@login_required
def copy_code():
    """Copy referral code to clipboard (JSON response)."""
    user = current_user()
    if not user:
        return jsonify({"error": "not authenticated"}), 401

    code = generate_referral_code(session["user_id"])
    return jsonify({"code": code, "success": True})
