// Package agent provides the self-service API key management endpoints
// (Phase 2, plan §2.2). Create lives in create.go (P2-T5), List/Get in
// list_get.go (P2-T6), Revoke in revoke.go (P2-T7), Rotate in rotate.go
// (P2-T8), Usage in usage.go (P5-T2); this file holds the Handler skeleton
// and shared helpers.
package agent

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"security-center-backend/internal/config"
	"security-center-backend/internal/repository"
	"security-center-backend/internal/service/jwt"
)

type Handler struct {
	repo  repository.APIKeyRepository
	cfg   config.AgentConfig
	usage usageStatsQuerier
	users whoamiUserLookup
}

// New builds the Handler. When a *gorm.DB is supplied (production wiring),
// the default MySQL-backed usage stats querier and whoami user lookup are
// injected; tests construct without it and swap in fakes via the unexported
// fields (whoami then degrades to claims-only fields).
func New(repo repository.APIKeyRepository, cfg config.AgentConfig, db ...*gorm.DB) *Handler {
	h := &Handler{repo: repo, cfg: cfg}
	if len(db) > 0 && db[0] != nil {
		h.usage = newGormUsageStatsQuerier(db[0])
		h.users = newGormWhoamiUserLookup(db[0])
	}
	return h
}

// currentUser extracts the authenticated claims injected by the auth middleware.
func currentUser(c *gin.Context) *jwt.Claims {
	claimsValue, ok := c.Get("current_user")
	if !ok {
		return nil
	}
	claims, ok := claimsValue.(*jwt.Claims)
	if !ok {
		return nil
	}
	return claims
}

// List handles GET /agent/api-keys (P2-T6), implemented in list_get.go.

// Get handles GET /agent/api-keys/:id (P2-T6), implemented in list_get.go.

// Revoke handles DELETE /agent/api-keys/:id (P2-T7), implemented in revoke.go.

// Rotate (POST /agent/api-keys/:id/rotate, P2-T8) is implemented in rotate.go.

// Usage (GET /agent/api-keys/:id/usage, P5-T2) is implemented in usage.go.
