package ui

import (
	"net/http"

	"git.wntrmute.dev/mc/mcias/internal/db"
	"git.wntrmute.dev/mc/mcias/internal/model"
)

// handleDashboard renders the main dashboard page.  Admin users see account
// counts and recent audit events; non-admin users see a welcome page.
func (u *UIServer) handleDashboard(w http.ResponseWriter, r *http.Request) {
	csrfToken, err := u.setCSRFCookies(w)
	if err != nil {
		u.logger.Error("set CSRF cookies", "error", err)
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}

	admin := isAdmin(r)

	data := DashboardData{
		PageData: PageData{CSRFToken: csrfToken, ActorName: u.actorName(r), IsAdmin: admin},
	}

	if admin {
		accounts, err := u.db.ListAccounts()
		if err != nil {
			u.renderError(w, r, http.StatusInternalServerError, "failed to load accounts")
			return
		}

		for _, a := range accounts {
			data.TotalAccounts++
			if a.Status == model.AccountStatusActive {
				data.ActiveAccounts++
			}
		}

		events, _, err := u.db.ListAuditEventsPaged(db.AuditQueryParams{Limit: 10, Offset: 0})
		if err != nil {
			u.logger.Warn("load recent audit events", "error", err)
			events = nil
		}
		data.RecentEvents = events
	}

	u.render(w, "dashboard", data)
}
