// components/main/settingsPageComponents/GeneralSettings.tsx
import bcrypt from "bcryptjs";
import { generateToken } from "../utils/cryptoUtils";
import USERS from "../config/users";
import { setAdminLoggedIn } from "@/redux/slices/authSlice"; // ✅ Wichtig
import { AppDispatch } from "@/redux/store"; // Import your AppDispatch type

const handleAdminLogin = (
  username: string,
  password: string,
  onSuccess: () => void,
  onError: (message: string) => void,
  dispatch: AppDispatch // Use the correct dispatch type
) => {
  const user = USERS.Admin;
  bcrypt.compare(password, user.password, (err, isMatch) => {
    if (isMatch) {
      const token = generateToken(user);
      sessionStorage.setItem("token", token);
      localStorage.setItem("isAdminLoggedIn", "true");

      dispatch(setAdminLoggedIn(true)); // ✅ Redux-Status setzen

      onSuccess();
    } else {
      dispatch(setAdminLoggedIn(false)); // optional
      onError(
        "Login fehlgeschlagen. Bitte überprüfen Sie Benutzername und Passwort."
      );
    }
  });
};

export default handleAdminLogin;
