// components/main/settingsPageComponents/hooks/useAdminAuth.ts
import { useState, useEffect } from "react";
import CryptoJS from "crypto-js";

/**
 * Entschlüsselt den gespeicherten Token (AES) aus sessionStorage.
 */
function decryptToken(encryptedToken: string) {
  const encryptionKey = process.env.NEXT_PUBLIC_ENCRYPTION_KEY;
  const encryptionIV = process.env.NEXT_PUBLIC_ENCRYPTION_IV;

  if (!encryptionKey || !encryptionIV) {
    throw new Error("Encryption key or IV is not defined.");
  }

  const key = CryptoJS.enc.Utf8.parse(encryptionKey);
  const iv = CryptoJS.enc.Utf8.parse(encryptionIV);

  const decrypted = CryptoJS.AES.decrypt(encryptedToken, key, { iv });
  return JSON.parse(decrypted.toString(CryptoJS.enc.Utf8));
}

export function useAdminAuth(showModal: boolean) {
  const [isAdminLoggedIn, setAdminLoggedIn] = useState(false);

  /**
   * Loggt den Admin aus und löscht token + localStorage
   */
  function logoutAdmin() {
    sessionStorage.removeItem("token");
    localStorage.setItem("isAdminLoggedIn", "false");
    setAdminLoggedIn(false);
  }

  useEffect(() => {
    if (showModal) {
      const token = sessionStorage.getItem("token");

      if (token) {
        try {
          const { exp } = decryptToken(token);

          // ✅ Token gültig
          if (Date.now() < exp) {
            localStorage.setItem("isAdminLoggedIn", "true");
            setAdminLoggedIn(true);
            return;
          }
        } catch (error) {
          console.error("❌ Token-Entschlüsselung fehlgeschlagen:", error);
        }
      }

      // 🔁 Fallback: prüfe ob localStorage Adminstatus hält
      const fromLocalStorage = localStorage.getItem("isAdminLoggedIn");
      if (fromLocalStorage === "true") {
        setAdminLoggedIn(true);
      } else {
        logoutAdmin();
      }
    }
  }, [showModal]);

  return { isAdminLoggedIn, logoutAdmin };
}
