package routes

import (
	"bssapp-backend/auth"
	"bssapp-backend/internal/auditlog"
	"bssapp-backend/repository"
	"database/sql"
	"encoding/json"
	"github.com/gorilla/mux"
	"golang.org/x/crypto/bcrypt"
	"net/http"
	"strconv"
)

type AdminResetPasswordRequest struct {
	Password string `json:"password"` // opsiyonel
}

func AdminResetPasswordHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		claims, ok := auth.GetClaimsFromContext(r.Context())
		if !ok || claims == nil {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
		// ---------------------------------------------------
		// 1️⃣ USER ID
		// ---------------------------------------------------
		idStr := mux.Vars(r)["id"]
		userID, err := strconv.ParseInt(idStr, 10, 64)
		if err != nil || userID <= 0 {
			http.Error(w, "invalid user id", http.StatusBadRequest)
			return
		}

		// ---------------------------------------------------
		// 2️⃣ PAYLOAD (opsiyonel)
		// ---------------------------------------------------
		var req AdminResetPasswordRequest
		_ = json.NewDecoder(r.Body).Decode(&req)

		// parola verilmediyse backend üretir
		password := req.Password
		if password == "" {
			password = "Temp123!" // 👉 istersek random generator ekleriz
		}

		// ---------------------------------------------------
		// 3️⃣ HASH
		// ---------------------------------------------------
		hash, err := bcrypt.GenerateFromPassword(
			[]byte(password),
			bcrypt.DefaultCost,
		)
		if err != nil {
			http.Error(w, "password hash error", http.StatusInternalServerError)
			return
		}

		// ---------------------------------------------------
		// 4️⃣ UPDATE mk_dfusr
		// ---------------------------------------------------
		res, err := db.Exec(`
			UPDATE mk_dfusr
			SET
				password_hash = $1,
				force_password_change = true,
				password_updated_at = NOW(),
				updated_at = NOW()
			WHERE id = $2
		`, string(hash), userID)

		if err != nil {
			http.Error(w, "password reset failed", http.StatusInternalServerError)
			return
		}

		affected, _ := res.RowsAffected()
		if affected == 0 {
			_, err = db.Exec(`
				UPDATE dfusr
				SET
					upass = $1,
					force_password_change = true,
					last_updated_date = NOW()
				WHERE id = $2
				  AND is_active = true
			`, string(hash), userID)

			if err != nil {
				http.Error(w, "legacy password reset failed", http.StatusInternalServerError)
				return
			}
		}

		// ---------------------------------------------------
		// 5️⃣ REFRESH TOKEN REVOKE
		// ---------------------------------------------------
		_ = repository.
			NewRefreshTokenRepository(db).
			RevokeAllForUser(userID)

		// ---------------------------------------------------
		// 6️⃣ AUDIT
		// ---------------------------------------------------
		auditlog.Write(auditlog.ActivityLog{
			ActionType:     "ADMIN_PASSWORD_RESET",
			ActionCategory: "security",
			ActionTarget:   "mk_dfusr.id",
			IsSuccess:      true,
		})

		// ---------------------------------------------------
		// 7️⃣ RESPONSE
		// ---------------------------------------------------
		_ = json.NewEncoder(w).Encode(map[string]any{
			"success": true,
		})
	}
}
