package main

import (
	"database/sql"
	"math/rand/v2"
	"net/http"
	"time"

	"github.com/go-chi/chi/v5"
	"golang.org/x/crypto/bcrypt"
)

func createUser(username, password string) error {
	uid := int64(rand.IntN(99999999))
	now := time.Now().Unix()

	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	_, err = db.Exec(
		`INSERT INTO user (uid, created_at, username, password) VALUES (?, ?, ?, ?)`,
		uid, now, username, hash,
	)
	return err
}

// idFromUsername liefert die interne id oder 0, wenn der Nutzer nicht existiert.
func idFromUsername(username string) int64 {
	var id int64
	if err := db.QueryRow(`SELECT id FROM user WHERE username = ?`, username).Scan(&id); err != nil {
		return 0
	}
	return id
}

func handleUserPage(w http.ResponseWriter, r *http.Request) {
	username := chi.URLParam(r, "username")

	var uid, createdAt int64
	err := db.QueryRow(`SELECT uid, created_at FROM user WHERE username = ?`, username).Scan(&uid, &createdAt)
	if err != nil {
		writeError(w, http.StatusNotFound, "Nutzer nicht gefunden")
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"uid":        uid,
		"username":   username,
		"created_at": createdAt,
	})
}

func handleUserInfo(w http.ResponseWriter, r *http.Request) {
	uid := uidFromContext(r.Context())

	var createdAt, lastLogin sql.NullInt64
	var username string
	err := db.QueryRow(
		`SELECT created_at, last_login, username FROM user WHERE uid = ?`, uid,
	).Scan(&createdAt, &lastLogin, &username)
	if err != nil {
		writeError(w, http.StatusNotFound, "Nutzer nicht gefunden")
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"uid":        uid,
		"username":   username,
		"created_at": createdAt.Int64,
		"last_login": lastLogin.Int64,
	})
}

func handleUserDelete(w http.ResponseWriter, r *http.Request) {
	writeError(w, http.StatusNotImplemented, "Account-Löschung ist noch nicht implementiert")
}
