// @vitest-environment node

import { describe, it, expect, vi, beforeEach } from "vitest";

// Mock the env module to simulate an unconfigured deployment.
// The fetch wrappers must never touch the client when !isConfigured.
vi.mock("@/sanity/env", () => ({
  isConfigured: false,
  projectId: undefined,
  dataset: "production",
  apiVersion: "2026-03-01",
  readToken: undefined,
  webhookSecret: undefined,
}));

// Spy on getClient so we can assert it is NOT invoked in the fallback path.
const getClientSpy = vi.fn(() => {
  throw new Error("getClient should not be called when Sanity is not configured");
});
vi.mock("@/sanity/client", () => ({
  getClient: () => getClientSpy(),
}));

describe("sanityFetch wrappers (fallback path)", () => {
  beforeEach(() => {
    getClientSpy.mockClear();
  });

  it("sanityFetchList returns [] and does not touch the client when unconfigured", async () => {
    const { sanityFetchList } = await import("@/sanity/fetch");
    const result = await sanityFetchList<{ _id: string }>({
      query: "*[_type == 'post']",
      params: { start: 0, end: 20 },
      tags: ["post"],
    });
    expect(result).toEqual([]);
    expect(getClientSpy).not.toHaveBeenCalled();
  });

  it("sanityFetchOne returns null and does not touch the client when unconfigured", async () => {
    const { sanityFetchOne } = await import("@/sanity/fetch");
    const result = await sanityFetchOne<{ _id: string }>({
      query: "*[_type == 'post'][0]",
      params: { slug: "hello" },
      tags: ["post", "post:hello"],
    });
    expect(result).toBeNull();
    expect(getClientSpy).not.toHaveBeenCalled();
  });
});
