'use client';

// AUTO-GENERATED by openapi_processor / ts.hooks
// Get current user profile
// DO NOT EDIT — re-run `make gen`.

import useSWR from "swr";
import type { SWRConfiguration } from "swr";
import { CfgAccountsProfile } from "../../sdk.gen";
import type { CfgAccountsProfileRetrieveData, CfgAccountsProfileRetrieveResponses } from "../../types.gen";
import { UserSchema } from "../schemas/User";

type Result = CfgAccountsProfileRetrieveResponses[keyof CfgAccountsProfileRetrieveResponses];

/**
 * 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 useCfgAccountsProfileRetrieve(
  args?: Omit<CfgAccountsProfileRetrieveData, "url" | "body">,
  config?: HookConfig,
) {
  const { enabled = true, ...swrConfig } = config ?? {};
  const key = enabled ? ["cfg_accounts_profile_retrieve", args ?? {}] as const : null;
  return useSWR<Result>(
    key,
    async () => {
      const res = await CfgAccountsProfile.cfgAccountsProfileRetrieve({ ...(args ?? {}), throwOnError: true } as never);
      const data = res.data as Result;
      const parsed = UserSchema.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_profile_retrieve",
            method: "GET",
            path: "/cfg/accounts/profile/",
            issues: parsed.error.issues,
            data,
          },
        );
        if (typeof window !== "undefined") {
          try {
            window.dispatchEvent(
              new CustomEvent("zod-validation-error", {
                detail: {
                  operation: "cfg_accounts_profile_retrieve",
                  method: "GET",
                  path: "/cfg/accounts/profile/",
                  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,
  );
}
