'use client';

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

import useSWRMutation from "swr/mutation";
import type { SWRMutationConfiguration } from "swr/mutation";
import { CfgAccountsOauth } from "../../sdk.gen";
import type { CfgAccountsOauthGithubAuthorizeCreateData, CfgAccountsOauthGithubAuthorizeCreateResponses } from "../../types.gen";
import { OAuthAuthorizeResponseSchema } from "../schemas/OAuthAuthorizeResponse";

type Args = Omit<CfgAccountsOauthGithubAuthorizeCreateData, "url">;
type Result = CfgAccountsOauthGithubAuthorizeCreateResponses[keyof CfgAccountsOauthGithubAuthorizeCreateResponses];

export function useCfgAccountsOauthGithubAuthorizeCreate(
  config?: SWRMutationConfiguration<Result, Error, readonly ["cfg_accounts_oauth_github_authorize_create"], Args>,
) {
  return useSWRMutation<Result, Error, readonly ["cfg_accounts_oauth_github_authorize_create"], Args>(
    ["cfg_accounts_oauth_github_authorize_create"] as const,
    async (_key, { arg }: { arg: Args }) => {
      const res = await CfgAccountsOauth.cfgAccountsOauthGithubAuthorizeCreate({ ...arg, throwOnError: true } as never);
      const data = res.data as Result;
      const parsed = OAuthAuthorizeResponseSchema.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_github_authorize_create",
            method: "POST",
            path: "/cfg/accounts/oauth/github/authorize/",
            issues: parsed.error.issues,
            data,
          },
        );
        if (typeof window !== "undefined") {
          try {
            window.dispatchEvent(
              new CustomEvent("zod-validation-error", {
                detail: {
                  operation: "cfg_accounts_oauth_github_authorize_create",
                  method: "POST",
                  path: "/cfg/accounts/oauth/github/authorize/",
                  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;
    },
    config,
  );
}
