'use client';

// AUTO-GENERATED by openapi_processor / ts.hooks
// GET /cfg/totp/backup-codes/
// DO NOT EDIT — re-run `make gen`.

import useSWR from "swr";
import type { SWRConfiguration } from "swr";
import { CfgTotpBackupCodes } from "../../sdk.gen";
import type { CfgTotpBackupCodesRetrieveData, CfgTotpBackupCodesRetrieveResponses } from "../../types.gen";
import { BackupCodesStatusSchema } from "../schemas/BackupCodesStatus";

type Result = CfgTotpBackupCodesRetrieveResponses[keyof CfgTotpBackupCodesRetrieveResponses];

/**
 * Optional `enabled` flag — when `false`, the SWR key becomes `null` and
 * no request is made. Use for gated endpoints (auth-required, feature
 * flags, "fetch only when X is selected"). The flag is stripped before
 * being forwarded to `useSWR` so the underlying SWR config stays pristine.
 */
type HookConfig = SWRConfiguration<Result> & { enabled?: boolean };

export function useCfgTotpBackupCodesRetrieve(
  args?: Omit<CfgTotpBackupCodesRetrieveData, "url" | "body">,
  config?: HookConfig,
) {
  const { enabled = true, ...swrConfig } = config ?? {};
  const key = enabled ? ["cfg_totp_backup_codes_retrieve", args ?? {}] as const : null;
  return useSWR<Result>(
    key,
    async () => {
      const res = await CfgTotpBackupCodes.cfgTotpBackupCodesRetrieve({ ...(args ?? {}), throwOnError: true } as never);
      const data = res.data as Result;
      const parsed = BackupCodesStatusSchema.safeParse(data);
      if (!parsed.success) {
        // Log first so the failure is always visible, even if the
        // event handler swallows it.
        console.warn(
          "[zod] response did not match schema",
          {
            operation: "cfg_totp_backup_codes_retrieve",
            method: "GET",
            path: "/cfg/totp/backup-codes/",
            issues: parsed.error.issues,
            data,
          },
        );
        if (typeof window !== "undefined") {
          try {
            window.dispatchEvent(
              new CustomEvent("zod-validation-error", {
                detail: {
                  operation: "cfg_totp_backup_codes_retrieve",
                  method: "GET",
                  path: "/cfg/totp/backup-codes/",
                  issues: parsed.error.issues,
                  data,
                  timestamp: new Date(),
                },
                bubbles: true,
                cancelable: false,
              }),
            );
          } catch {
            // Event dispatch is best-effort.
          }
        }
        return data;
      }
      return parsed.data as unknown as Result;
    },
    swrConfig,
  );
}
