"use client";

import { useState } from "react";
import {
  getSecurityAudit,
  fixSecurityIssue,
  type SecurityAuditResult,
} from "@/lib/api";

export function useAdminSecurity() {
  const [securityAudit, setSecurityAudit] = useState<SecurityAuditResult | null>(null);
  const [securityLoading, setSecurityLoading] = useState(false);
  const [securityError, setSecurityError] = useState("");
  const [fixLoading, setFixLoading] = useState<string | null>(null);
  const [fixMessage, setFixMessage] = useState("");

  async function runSecurityAudit() {
    setSecurityLoading(true);
    setSecurityError("");
    setFixMessage("");
    try {
      const result = await getSecurityAudit();
      setSecurityAudit(result);
    } catch {
      setSecurityError("Security-Audit konnte nicht ausgeführt werden.");
    } finally {
      setSecurityLoading(false);
    }
  }

  async function runFix(action: string) {
    setFixLoading(action);
    setFixMessage("");
    setSecurityError("");
    try {
      const res = await fixSecurityIssue(action);
      setFixMessage(res.message);
      await runSecurityAudit();
    } catch (e: unknown) {
      setSecurityError(e instanceof Error ? e.message : "Fix fehlgeschlagen.");
    } finally {
      setFixLoading(null);
    }
  }

  return {
    securityAudit,
    securityLoading,
    securityError,
    fixLoading,
    fixMessage,
    runSecurityAudit,
    runFix,
  };
}
