from flask import Blueprint, request, jsonify, current_app
from flask_login import login_required, current_user
from utils.email_service import EmailService

email_actions_bp = Blueprint("email_actions", __name__, url_prefix="/api/email")

def require_admin():
    # Adjust to your own RBAC flag/role
    if not getattr(current_user, "is_admin", False):
        return False
    return True

@email_actions_bp.post("/onboarding")
@login_required
def api_onboarding_send():
    data = request.get_json(silent=True) or {}

    # accept either "email" or "description" as the recipient
    to = (data.get("email") or data.get("description") or "").strip()
    name = (data.get("name") or "there").strip()

    # accept either "link" or "full_link"
    link = (data.get("link") or data.get("full_link") or "").strip()

    # fallback/default
    try:
        expiry_hours = int(data.get("expiry_hours") or 48)
    except Exception:
        expiry_hours = 48

    if not to or not link:
        return jsonify({"ok": False, "message": "email and link are required"}), 400

    # (optional) quick email format guard
    # import re
    # if not re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", to):
    #     return jsonify({"ok": False, "message": "description is not a valid email"}), 400

    EmailService.send(
        "onboarding_link",
        to=to,
        ctx={"name": name, "link": link, "expiry_hours": expiry_hours}
    )
    return jsonify({"ok": True, "message": f"Onboarding email queued to {to}."}), 200


@email_actions_bp.post("/password-set")
@login_required
def api_password_set():
    data = request.get_json(silent=True) or {}

    to   = (data.get("email") or "").strip()
    name = (data.get("name")  or "").strip()
    link = (data.get("link")  or "").strip()

    if not to or not link:
        return jsonify({"ok": False, "message": "email and link are required"}), 400

    try:
        EmailService.send(
            template="password_set",   # see templates below
            to=to,
            ctx={"name": name or "there", "link": link},
            async_send=True
        )
        return jsonify({"ok": True, "message": f"Password‑set email queued to {to}."}), 200
    except Exception as e:
        current_app.logger.exception("password-set email failed")
        return jsonify({"ok": False, "message": str(e)}), 500