package xss

import (
	"context"
	"encoding/json"
	"log"
	"net/http"

	"github.com/Vomitblood/cspj-application/server/internal/db"
)

// fetch the email of the user, frontend will display it insecurely for xss
func FetchUserDetails(w http.ResponseWriter, r *http.Request) {
	var credentials struct {
		Id string `json:"id"`
	}

	if err := json.NewDecoder(r.Body).Decode(&credentials); err != nil {
		http.Error(w, "Invalid request format", http.StatusBadRequest)
		return
	}
	defer r.Body.Close()

	// construct the query
	query := "SELECT id, username, email FROM users WHERE id = $1"
	var id int
	var username string
	var email string
	err := db.DbPool.QueryRow(context.Background(), query, credentials.Id).Scan(&id, &username, &email)
	if err != nil {
		http.Error(w, "Invalid credentials", http.StatusUnauthorized)
		return
	}

	// send back the response if great success
	response := map[string]interface{}{
		"id":       id,
		"username": username,
		"email":    email,
	}
	if err := json.NewEncoder(w).Encode(response); err != nil {
		http.Error(w, "Failed to encode response", http.StatusInternalServerError)
		log.Printf("JSON encoding error: %v", err)
	}
}
