"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { Button } from "@open-mercato/ui/primitives/button";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { ErrorMessage } from "@open-mercato/ui/backend/detail";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { hasFeature } from "@open-mercato/shared/security/features";
const MANAGE_FEATURE = "configs.cache.manage";
const API_PATH = "/api/configs/cache";
const CACHE_MUTATION_CONTEXT_ID = "configs-cache-panel";
function CachePanel() {
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [state, setState] = React.useState({ loading: true, error: null, stats: null });
  const [canManage, setCanManage] = React.useState(false);
  const [checkingFeature, setCheckingFeature] = React.useState(true);
  const [purgingAll, setPurgingAll] = React.useState(false);
  const [segmentPurges, setSegmentPurges] = React.useState({});
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: CACHE_MUTATION_CONTEXT_ID,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const cacheMutationContext = React.useMemo(
    () => ({
      formId: CACHE_MUTATION_CONTEXT_ID,
      resourceKind: "configs.cache",
      retryLastMutation
    }),
    [retryLastMutation]
  );
  const loadStats = React.useCallback(async () => {
    setState((current) => ({ ...current, loading: true, error: null }));
    try {
      const stats2 = await readApiResultOrThrow(API_PATH, void 0, {
        errorMessage: t("configs.cache.loadError", "Failed to load cache statistics.")
      });
      setState({ loading: false, error: null, stats: stats2 });
    } catch (error) {
      const message = error instanceof Error && error.message ? error.message : t("configs.cache.loadError", "Failed to load cache statistics.");
      setState({ loading: false, error: message, stats: null });
    }
  }, [t]);
  React.useEffect(() => {
    loadStats().catch(() => {
    });
  }, [loadStats]);
  React.useEffect(() => {
    let cancelled = false;
    async function checkManageFeature() {
      try {
        const payload = await readApiResultOrThrow(
          "/api/auth/feature-check",
          {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ features: [MANAGE_FEATURE] })
          },
          {
            errorMessage: t("configs.cache.loadError", "Failed to load cache statistics."),
            allowNullResult: true
          }
        );
        if (cancelled) return;
        const granted = Array.isArray(payload?.granted) ? payload.granted.filter((feature) => typeof feature === "string") : [];
        const canManageFeature = payload?.ok === true || hasFeature(granted, MANAGE_FEATURE);
        setCanManage(canManageFeature);
      } catch {
        if (!cancelled) setCanManage(false);
      } finally {
        if (!cancelled) setCheckingFeature(false);
      }
    }
    checkManageFeature().catch(() => {
    });
    return () => {
      cancelled = true;
    };
  }, [t]);
  const handleRefresh = React.useCallback(() => {
    loadStats().catch(() => {
    });
  }, [loadStats]);
  const handlePurgeAll = React.useCallback(async () => {
    if (!canManage || purgingAll) return;
    const confirmed = await confirm({
      title: t("configs.cache.purgeAllConfirm", "Purge all cached entries for this tenant?"),
      variant: "destructive"
    });
    if (!confirmed) return;
    setPurgingAll(true);
    try {
      const payload = await runMutation({
        operation: () => readApiResultOrThrow(
          API_PATH,
          {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ action: "purgeAll" })
          },
          {
            errorMessage: t("configs.cache.purgeError", "Failed to purge cache segment."),
            allowNullResult: true
          }
        ),
        context: cacheMutationContext,
        mutationPayload: { action: "purgeAll" }
      });
      const stats2 = payload?.stats;
      if (stats2) {
        setState({ loading: false, error: null, stats: stats2 });
      } else {
        handleRefresh();
      }
      flash(t("configs.cache.purgeAllSuccess", "Cache cleared."), "success");
      setSegmentPurges({});
    } catch (error) {
      const message = error instanceof Error && error.message ? error.message : t("configs.cache.purgeError", "Failed to purge cache segment.");
      flash(message, "error");
    } finally {
      setPurgingAll(false);
    }
  }, [canManage, confirm, purgingAll, t, handleRefresh, runMutation, cacheMutationContext]);
  const handlePurgeSegment = React.useCallback(async (segment) => {
    if (!canManage || segmentPurges[segment]) return;
    const confirmed = await confirm({
      title: t("configs.cache.purgeSegmentConfirm", "Purge cached entries for this segment?"),
      variant: "destructive"
    });
    if (!confirmed) return;
    setSegmentPurges((prev) => ({ ...prev, [segment]: true }));
    try {
      const payload = await runMutation({
        operation: () => readApiResultOrThrow(
          API_PATH,
          {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ action: "purgeSegment", segment })
          },
          {
            errorMessage: t("configs.cache.purgeError", "Failed to purge cache segment."),
            allowNullResult: true
          }
        ),
        context: cacheMutationContext,
        mutationPayload: { action: "purgeSegment", segment }
      });
      const stats2 = payload?.stats;
      if (stats2) {
        setState({ loading: false, error: null, stats: stats2 });
      } else {
        handleRefresh();
      }
      const deleted = typeof payload?.deleted === "number" ? payload.deleted : 0;
      flash(
        t("configs.cache.purgeSegmentSuccess", {
          segment,
          count: deleted
        }),
        "success"
      );
    } catch (error) {
      const message = error instanceof Error && error.message ? error.message : t("configs.cache.purgeError", "Failed to purge cache segment.");
      flash(message, "error");
    } finally {
      setSegmentPurges((prev) => {
        const next = { ...prev };
        delete next[segment];
        return next;
      });
    }
  }, [canManage, confirm, segmentPurges, t, handleRefresh, runMutation, cacheMutationContext]);
  if (state.loading) {
    return /* @__PURE__ */ jsxs("section", { className: "space-y-3 rounded-lg border bg-background p-6", children: [
      ConfirmDialogElement,
      /* @__PURE__ */ jsxs("header", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("configs.cache.title", "Cache overview") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("configs.cache.description", "Inspect cached responses and clear segments when necessary.") })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
        /* @__PURE__ */ jsx(Spinner, { className: "h-4 w-4" }),
        t("configs.cache.loading", "Loading cache statistics\u2026")
      ] })
    ] });
  }
  if (state.error) {
    return /* @__PURE__ */ jsxs("section", { className: "space-y-3 rounded-lg border bg-background p-6", children: [
      ConfirmDialogElement,
      /* @__PURE__ */ jsxs("header", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("configs.cache.title", "Cache overview") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("configs.cache.description", "Inspect cached responses and clear segments when necessary.") })
      ] }),
      /* @__PURE__ */ jsx(ErrorMessage, { label: state.error }),
      /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: /* @__PURE__ */ jsx(Button, { variant: "outline", type: "button", onClick: handleRefresh, children: t("configs.cache.retry", "Retry") }) })
    ] });
  }
  const stats = state.stats;
  const canShowActions = !checkingFeature && canManage;
  return /* @__PURE__ */ jsxs("section", { className: "space-y-6 rounded-lg border bg-background p-6", children: [
    /* @__PURE__ */ jsxs("header", { className: "flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("configs.cache.title", "Cache overview") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("configs.cache.description", "Inspect cached responses and clear segments when necessary.") }),
        stats ? /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
            "configs.cache.generatedAt",
            "Stats generated {{timestamp}}",
            { timestamp: new Date(stats.generatedAt).toLocaleString() }
          ) }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
            "configs.cache.totalEntries",
            "{{count}} cached entries",
            { count: stats.totalKeys }
          ) })
        ] }) : null
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", type: "button", onClick: handleRefresh, children: t("configs.cache.refresh", "Refresh") }),
        canShowActions ? /* @__PURE__ */ jsx(Button, { variant: "destructive", type: "button", disabled: purgingAll, onClick: () => {
          void handlePurgeAll();
        }, children: purgingAll ? t("configs.cache.purgeAllLoading", "Purging\u2026") : t("configs.cache.purgeAll", "Purge all cache") }) : null
      ] })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "space-y-4 rounded-lg border bg-card p-4", children: stats && stats.segments.length ? /* @__PURE__ */ jsx("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsxs("table", { className: "w-full min-w-[560px] text-sm", children: [
      /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "text-xs uppercase tracking-wide text-muted-foreground", children: [
        /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: t("configs.cache.table.segment", "Segment") }),
        /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: t("configs.cache.table.path", "Path") }),
        /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: t("configs.cache.table.method", "Method") }),
        /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: t("configs.cache.table.count", "Cached keys") }),
        canShowActions ? /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right", children: t("configs.cache.table.actions", "Actions") }) : null
      ] }) }),
      /* @__PURE__ */ jsx("tbody", { children: stats.segments.map((segment) => {
        const isPurging = !!segmentPurges[segment.segment];
        return /* @__PURE__ */ jsxs("tr", { className: "border-t", children: [
          /* @__PURE__ */ jsx("td", { className: "px-3 py-2 align-top font-medium", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
            /* @__PURE__ */ jsx("span", { children: segment.segment }),
            segment.resource ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: segment.resource }) : null
          ] }) }),
          /* @__PURE__ */ jsx("td", { className: "px-3 py-2 align-top", children: /* @__PURE__ */ jsx("code", { className: "text-xs text-muted-foreground", children: segment.path ?? t("configs.cache.table.pathUnknown", "n/a") }) }),
          /* @__PURE__ */ jsx("td", { className: "px-3 py-2 align-top", children: /* @__PURE__ */ jsx("span", { className: "text-xs uppercase text-muted-foreground", children: segment.method ?? "GET" }) }),
          /* @__PURE__ */ jsx("td", { className: "px-3 py-2 align-top", children: t("configs.cache.table.countValue", "{{count}} keys", { count: segment.keyCount }) }),
          canShowActions ? /* @__PURE__ */ jsx("td", { className: "px-3 py-2 align-top text-right", children: /* @__PURE__ */ jsx(
            Button,
            {
              variant: "outline",
              size: "sm",
              type: "button",
              disabled: isPurging,
              onClick: () => {
                void handlePurgeSegment(segment.segment);
              },
              children: isPurging ? t("configs.cache.purgeSegmentLoading", "Purging\u2026") : t("configs.cache.purgeSegment", "Purge segment")
            }
          ) }) : null
        ] }, segment.segment);
      }) })
    ] }) }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("configs.cache.empty", "No cached responses for this tenant.") }) }),
    ConfirmDialogElement
  ] });
}
var CachePanel_default = CachePanel;
export {
  CachePanel,
  CachePanel_default as default
};
//# sourceMappingURL=CachePanel.js.map
