package api

import (
	"encoding/json"
	"net/http"
	"strconv"
)

// GET /api/v1/users
func (h *Handler) listUsers(w http.ResponseWriter, r *http.Request) {
	users, err := h.db.GetUsers()
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Fehler beim Laden")
		return
	}
	writeJSON(w, http.StatusOK, users)
}

// POST /api/v1/users
func (h *Handler) createUser(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Username    string `json:"username"`
		Password    string `json:"password"`
		DisplayName string `json:"display_name"`
		Role        string `json:"role"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Username == "" || req.Password == "" {
		writeError(w, http.StatusBadRequest, "username und password sind erforderlich")
		return
	}
	if req.Role == "" {
		req.Role = "admin"
	}
	u, err := h.db.CreateUser(req.Username, req.Password, req.DisplayName, req.Role)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "User anlegen fehlgeschlagen")
		return
	}
	h.auditLog(r, "user.create", "user", "", req.Username, "")
	writeJSON(w, http.StatusCreated, u)
}

// PUT /api/v1/users/{id}/password
func (h *Handler) changePassword(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeError(w, http.StatusBadRequest, "Ungueltige ID")
		return
	}
	var req struct {
		Password string `json:"password"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Password == "" {
		writeError(w, http.StatusBadRequest, "password ist erforderlich")
		return
	}
	if len(req.Password) < 6 {
		writeError(w, http.StatusBadRequest, "Passwort muss mindestens 6 Zeichen lang sein")
		return
	}
	if err := h.db.ChangePassword(id, req.Password); err != nil {
		writeError(w, http.StatusInternalServerError, "Passwort aendern fehlgeschlagen")
		return
	}
	h.auditLog(r, "password.change", "user", strconv.Itoa(id), "", "")
	writeJSON(w, http.StatusOK, map[string]string{"message": "Passwort geaendert"})
}

// DELETE /api/v1/users/{id}
func (h *Handler) deleteUser(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.Atoi(r.PathValue("id"))
	if err != nil {
		writeError(w, http.StatusBadRequest, "Ungueltige ID")
		return
	}
	deleted, err := h.db.DeleteUser(id)
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Loeschen fehlgeschlagen")
		return
	}
	if !deleted {
		writeError(w, http.StatusNotFound, "User nicht gefunden")
		return
	}
	h.auditLog(r, "user.delete", "user", strconv.Itoa(id), "", "")
	writeJSON(w, http.StatusOK, map[string]string{"message": "User geloescht"})
}
