"""Zoho CRM sync status and admin actions."""

from flask import Blueprint, render_template, request, g, jsonify

from webapp.auth import role_required
from icp_db import get_zoho_sync_log, get_zoho_sync_stats
from zoho_client import is_configured

zoho_bp = Blueprint("zoho", __name__)


@zoho_bp.route("/zoho")
@role_required("admin")
def index():
    """Zoho sync status dashboard."""
    db = g.db
    stats = get_zoho_sync_stats(db)
    recent_log = get_zoho_sync_log(db, limit=50)
    configured = is_configured()

    return render_template(
        "zoho.html",
        stats=stats,
        recent_log=recent_log,
        configured=configured,
    )


@zoho_bp.route("/zoho/sync-all", methods=["POST"])
@role_required("admin")
def sync_all():
    """Manual bulk sync of all unsynced ICP contacts."""
    from zoho_sync import sync_all_unsynced
    db = g.db
    result = sync_all_unsynced(db)
    return render_template("partials/zoho_sync_result.html", result=result)


@zoho_bp.route("/zoho/sync/<int:contact_id>", methods=["POST"])
@role_required("admin")
def sync_one(contact_id):
    """Manual sync of a single contact."""
    from zoho_sync import sync_contact_to_zoho
    db = g.db
    result = sync_contact_to_zoho(db, contact_id)
    return jsonify(result)


@zoho_bp.route("/zoho/log")
@role_required("admin")
def log_table():
    """htmx partial: refreshable sync log table."""
    db = g.db
    recent_log = get_zoho_sync_log(db, limit=50)
    return render_template("partials/zoho_log_table.html", recent_log=recent_log)
