//
// Copyright 2026 James Pace
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// This Source Code Form is "Incompatible With Secondary Licenses", as
// defined by the Mozilla Public License, v. 2.0.
//

import { atomWithQuery } from "jotai-tanstack-query";

export async function fetchJson(url: string): Promise<any> {
  const resp = await fetch(url);
  if (!resp.ok) {
    throw new Error(`Network response was not ok: ${resp.statusText}`);
  }
  return resp.json();
}

interface CreateQueryAtomOptions {
  refetchInterval?: number;
  retry?: boolean;
}

export function createQueryAtom(url: string, options?: CreateQueryAtomOptions) {
  return atomWithQuery(() => ({
    queryKey: [url],
    queryFn: () => fetchJson(url),
    ...options,
  }));
}
