package api

import (
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"log"
	"net/http"
	"strconv"
)

// GET /api/v1/apikeys
func (h *Handler) listAPIKeys(w http.ResponseWriter, r *http.Request) {
	keys, err := h.db.ListAPIKeys()
	if err != nil {
		log.Printf("API-Keys laden fehlgeschlagen: %v", err)
		writeError(w, http.StatusInternalServerError, "Laden fehlgeschlagen")
		return
	}
	writeJSON(w, http.StatusOK, keys)
}

// POST /api/v1/apikeys
func (h *Handler) createAPIKey(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Name string `json:"name"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Name == "" {
		writeError(w, http.StatusBadRequest, "Parameter 'name' erforderlich")
		return
	}

	// Zufaelligen 32-Byte Key generieren
	b := make([]byte, 16)
	rand.Read(b)
	key := hex.EncodeToString(b)

	apiKey, err := h.db.CreateAPIKey(req.Name, key)
	if err != nil {
		log.Printf("API-Key erstellen fehlgeschlagen: %v", err)
		writeError(w, http.StatusInternalServerError, "Erstellen fehlgeschlagen")
		return
	}

	log.Printf("Neuer API-Key erstellt: %s (%s...)", apiKey.Name, key[:8])
	writeJSON(w, http.StatusCreated, apiKey)
}

// DELETE /api/v1/apikeys/{id}
func (h *Handler) deleteAPIKey(w http.ResponseWriter, r *http.Request) {
	idStr := r.PathValue("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		writeError(w, http.StatusBadRequest, "Ungueltige ID")
		return
	}

	if err := h.db.DeleteAPIKey(id); err != nil {
		writeError(w, http.StatusNotFound, "API-Key nicht gefunden")
		return
	}

	log.Printf("API-Key %d geloescht", id)
	writeJSON(w, http.StatusOK, map[string]string{"message": "API-Key geloescht"})
}
