'use client';

// AUTO-GENERATED by openapi_processor / ts.hooks
// List OAuth connections
// DO NOT EDIT — re-run `make gen`.

import useSWR from "swr";
import type { SWRConfiguration } from "swr";
import { CfgAccountsOauth } from "../../sdk.gen";
import type { CfgAccountsOauthConnectionsListData, CfgAccountsOauthConnectionsListResponses } from "../../types.gen";
import { cfg_accounts_oauth_connections_response_200_AutoRefSchema } from "../schemas/cfg_accounts_oauth_connections_response_200_AutoRef";

type Result = CfgAccountsOauthConnectionsListResponses[keyof CfgAccountsOauthConnectionsListResponses];

/**
 * 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 useCfgAccountsOauthConnectionsList(
  args?: Omit<CfgAccountsOauthConnectionsListData, "url" | "body">,
  config?: HookConfig,
) {
  const { enabled = true, ...swrConfig } = config ?? {};
  const key = enabled ? ["cfg_accounts_oauth_connections_list", args ?? {}] as const : null;
  return useSWR<Result>(
    key,
    async () => {
      const res = await CfgAccountsOauth.cfgAccountsOauthConnectionsList({ ...(args ?? {}), throwOnError: true } as never);
      const data = res.data as Result;
      const parsed = cfg_accounts_oauth_connections_response_200_AutoRefSchema.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_accounts_oauth_connections_list",
            method: "GET",
            path: "/cfg/accounts/oauth/connections/",
            issues: parsed.error.issues,
            data,
          },
        );
        if (typeof window !== "undefined") {
          try {
            window.dispatchEvent(
              new CustomEvent("zod-validation-error", {
                detail: {
                  operation: "cfg_accounts_oauth_connections_list",
                  method: "GET",
                  path: "/cfg/accounts/oauth/connections/",
                  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,
  );
}
