package api

import (
	"net/http"

	"archivmail/internal/auth"
	"archivmail/internal/userstore"
)

func (s *Server) handleSMTPStatus(w http.ResponseWriter, r *http.Request) {
	sess := sessionFromCtx(r.Context())
	tenantID := tenantFromCtx(r.Context())

	// domain_admin: return only their tenant's email statistics (no global daemon info)
	if sess != nil && !auth.HasRole(sess.Role, userstore.RoleSuperAdmin) {
		stats, err := s.store.StatsByTenant(r.Context(), tenantID)
		if err != nil {
			writeError(w, http.StatusInternalServerError, "failed to read stats")
			return
		}
		domains := []string{}
		if tenantID != nil && s.tenantStore != nil {
			if dd, derr := s.tenantStore.ListDomains(r.Context(), *tenantID); derr == nil {
				for _, d := range dd {
					domains = append(domains, d.Domain)
				}
			}
		}
		writeJSON(w, http.StatusOK, map[string]interface{}{
			"enabled":     true,
			"tenant_only": true,
			"domains":     domains,
			"total_mails": stats["count"],
			"total_bytes": stats["total_size"],
		})
		return
	}

	// superadmin: global daemon status
	if s.smtpDaemon == nil {
		writeJSON(w, http.StatusOK, map[string]interface{}{"enabled": false, "running": false})
		return
	}
	writeJSON(w, http.StatusOK, s.smtpDaemon.Status())
}

func (s *Server) handleStorageStats(w http.ResponseWriter, r *http.Request) {
	tenantID := tenantFromCtx(r.Context())
	stats, err := s.store.StatsByTenant(r.Context(), tenantID)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "failed to read storage stats")
		return
	}
	writeJSON(w, http.StatusOK, map[string]interface{}{
		"total_mails": stats["count"],
		"total_bytes": stats["total_size"],
	})
}
