"""
Dashboard domain: user dashboard and settings.
"""
from pathlib import Path

from quart import Blueprint, flash, g, redirect, render_template, request, url_for

from ..auth.routes import login_required, update_user
from ..core import count_where, csrf_protect, fetch_one, soft_delete, utcnow_iso
from ..i18n import get_translations

bp = Blueprint(
    "dashboard",
    __name__,
    template_folder=str(Path(__file__).parent / "templates"),
    url_prefix="/dashboard",
)


async def get_user_stats(user_id: int) -> dict:
    return {
        "scenarios": await count_where(
            "scenarios WHERE user_id = ? AND deleted_at IS NULL", (user_id,)
        ),
        "leads": await count_where(
            "lead_requests WHERE user_id = ?", (user_id,)
        ),
    }


@bp.route("/")
@login_required
async def index():
    # Supplier users go straight to the supplier dashboard
    supplier = await fetch_one(
        "SELECT id FROM suppliers WHERE claimed_by = ? AND tier IN ('growth', 'pro')",
        (g.user["id"],),
    )
    if supplier:
        return redirect(url_for("suppliers.dashboard"))

    stats = await get_user_stats(g.user["id"])
    return await render_template("index.html", stats=stats)


@bp.route("/settings", methods=["GET", "POST"])
@login_required
@csrf_protect
async def settings():
    if request.method == "POST":
        form = await request.form
        await update_user(
            g.user["id"],
            name=form.get("name", "").strip() or None,
            updated_at=utcnow_iso(),
        )
        t = get_translations(g.get("lang") or "en")
        await flash(t["dash_settings_saved"], "success")
        return redirect(url_for("dashboard.settings"))

    return await render_template("settings.html")


@bp.route("/delete-account", methods=["POST"])
@login_required
@csrf_protect
async def delete_account():
    from quart import session
    await soft_delete("users", g.user["id"])
    session.clear()
    t = get_translations(g.lang)
    await flash(t["dash_account_deleted"], "info")
    return redirect(url_for("public.landing"))
