package users

import (
	"log/slog"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/jackc/pgx/v5/pgxpool"

	"github.com/ultisuite/ulti-backend/internal/api/apiresponse"
	"github.com/ultisuite/ulti-backend/internal/api/apivalidate"
	"github.com/ultisuite/ulti-backend/internal/api/middleware"
	"github.com/ultisuite/ulti-backend/internal/permission"
	platformusers "github.com/ultisuite/ulti-backend/internal/users"
)

type Handler struct {
	db     *pgxpool.Pool
	logger *slog.Logger
}

func NewHandler(db *pgxpool.Pool) *Handler {
	return &Handler{
		db:     db,
		logger: slog.Default().With("component", "users-api"),
	}
}

func (h *Handler) Routes() chi.Router {
	r := chi.NewRouter()
	r.Get("/me", h.Me)
	return r
}

func (h *Handler) Me(w http.ResponseWriter, r *http.Request) {
	claims := middleware.ClaimsFromContext(r.Context())
	if claims == nil {
		apiresponse.WriteError(w, r, http.StatusUnauthorized, apiresponse.CodeAuthUnauthorized, "unauthorized", nil)
		return
	}

	state, err := platformusers.GetAccountState(r.Context(), h.db, claims.Sub)
	if err != nil {
		h.logger.Error("read account state", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	role := permission.DeriveAccountRole(state.PlatformAdmin, state.Status)

	apiresponse.WriteJSON(w, http.StatusOK, map[string]any{
		"sub":            claims.Sub,
		"email":          claims.Email,
		"name":           claims.Name,
		"status":         state.Status,
		"platform_admin": state.PlatformAdmin,
		"role":           role,
		"groups":         claims.Groups,
	})
}
