package users

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

	"git.schreifuchs.ch/schreifuchs/ng-blog/internal/auth"
	"git.schreifuchs.ch/schreifuchs/ng-blog/internal/model"
	"golang.org/x/crypto/bcrypt"
)

// ChangePassword handles changing a user's password by decoding a request, validating input, hashing the password, and updating the database.
func (s Service) ChangePassword(w http.ResponseWriter, r *http.Request) {
	var err error
	var req Password
	user := model.NewUser()

	if err = json.NewDecoder(r.Body).Decode(&req); err != nil {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}

	if claims, ok := auth.ExtractClaims(r.Context()); !ok {
		log.Println("Error: was not able to extract Claims")
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		user.ID = claims.UserID
	}

	if len([]byte(req.Password)) > 72 {
		fmt.Fprint(w, "Password to long, max 72 bytes")
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	if user.Password, err = bcrypt.GenerateFromPassword([]byte(req.Password), 6); err != nil {
		log.Println("Error: ", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	err = s.db.Model(&user).
		Where("id = ?", user.ID).
		Update("password", user.Password).
		Error
	if err != nil {
		log.Printf("Error: %v", err)
		w.WriteHeader(http.StatusInternalServerError)
	}
	w.WriteHeader(http.StatusOK)
}
