package auth

import (
	"bssapp-backend/internal/auditlog"
	"bssapp-backend/repository"
	"database/sql"
	"encoding/json"
	"net/http"
	"time"
)

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

		claims, ok := GetClaimsFromContext(r.Context())
		if !ok || claims == nil {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		userID := claims.ID

		_ = repository.NewRefreshTokenRepository(db).
			RevokeAllForUser(userID)

		http.SetCookie(w, &http.Cookie{
			Name:     "mk_refresh",
			Value:    "",
			Path:     "/",
			Expires:  time.Unix(0, 0),
			HttpOnly: true,
		})

		auditlog.Write(auditlog.ActivityLog{
			UserID:         auditlog.IntUserIDToUUID(int(userID)),
			ActionType:     "logout_all",
			ActionCategory: "auth",
			Description:    "user logged out from all devices",
			IsSuccess:      true,
		})

		_ = json.NewEncoder(w).Encode(map[string]bool{"success": true})
	}
}
