import secrets
import hashlib
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from app.extensions import db
from app.models.features import WhiteLabelConfig
from app.routes.admin import admin_required

whitelabel_bp = Blueprint("whitelabel", __name__, url_prefix="/whitelabel")


@whitelabel_bp.route("/")
@admin_required
def index():
    configs = WhiteLabelConfig.query.order_by(WhiteLabelConfig.created_at.desc()).all()
    return render_template("whitelabel/index.html", configs=configs)


@whitelabel_bp.route("/create", methods=["GET", "POST"])
@admin_required
def create():
    if request.method == "POST":
        raw_key = secrets.token_hex(32)
        config = WhiteLabelConfig(
            org_name=request.form.get("org_name", "").strip(),
            logo_url=request.form.get("logo_url", "").strip(),
            primary_color=request.form.get("primary_color", "#D2AF20").strip(),
            domain=request.form.get("domain", "").strip(),
            api_key_hash=hashlib.sha256(raw_key.encode()).hexdigest(),
        )
        db.session.add(config)
        db.session.commit()
        flash(f"Created. API Key (save it now): {raw_key}", "success")
        return redirect(url_for("whitelabel.index"))
    return render_template("whitelabel/create.html")


@whitelabel_bp.route("/toggle/<int:config_id>", methods=["POST"])
@admin_required
def toggle(config_id):
    config = WhiteLabelConfig.query.get_or_404(config_id)
    config.is_active = not config.is_active
    db.session.commit()
    flash(f"{'Activated' if config.is_active else 'Deactivated'} {config.org_name}.", "success")
    return redirect(url_for("whitelabel.index"))
