'use client';

// AUTO-GENERATED by openapi_processor / ts.hooks
// Get Centrifugo connection token
// DO NOT EDIT — re-run `make gen`.

import useSWR from "swr";
import type { SWRConfiguration } from "swr";
import { CfgCentrifugo } from "../../sdk.gen";
import type { CfgCentrifugoAuthTokenRetrieveData, CfgCentrifugoAuthTokenRetrieveResponses } from "../../types.gen";
import { ConnectionTokenResponseSchema } from "../schemas/ConnectionTokenResponse";

type Result = CfgCentrifugoAuthTokenRetrieveResponses[keyof CfgCentrifugoAuthTokenRetrieveResponses];

/**
 * 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 useCfgCentrifugoAuthTokenRetrieve(
  args?: Omit<CfgCentrifugoAuthTokenRetrieveData, "url" | "body">,
  config?: HookConfig,
) {
  const { enabled = true, ...swrConfig } = config ?? {};
  const key = enabled ? ["cfg_centrifugo_auth_token_retrieve", args ?? {}] as const : null;
  return useSWR<Result>(
    key,
    async () => {
      const res = await CfgCentrifugo.cfgCentrifugoAuthTokenRetrieve({ ...(args ?? {}), throwOnError: true } as never);
      const data = res.data as Result;
      const parsed = ConnectionTokenResponseSchema.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_centrifugo_auth_token_retrieve",
            method: "GET",
            path: "/cfg/centrifugo/auth/token/",
            issues: parsed.error.issues,
            data,
          },
        );
        if (typeof window !== "undefined") {
          try {
            window.dispatchEvent(
              new CustomEvent("zod-validation-error", {
                detail: {
                  operation: "cfg_centrifugo_auth_token_retrieve",
                  method: "GET",
                  path: "/cfg/centrifugo/auth/token/",
                  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,
  );
}
