"use client";

/**
 * Sanity Studio config for the OrthoGlobe editorial workspace.
 *
 * NOTE: this module is bundled into the Studio client and cannot use the
 * `server-only` `@/lib/env` helper. We read NEXT_PUBLIC_* vars directly
 * from process.env and fall back to "placeholder" so that `pnpm build`
 * succeeds in environments without Sanity credentials (the Studio UI
 * just won't connect to a real project until the env is populated).
 */

import { visionTool } from "@sanity/vision";
import { defineConfig } from "sanity";
import { structureTool } from "sanity/structure";

import { schema } from "./src/sanity/schemas";

const projectId =
  process.env.NEXT_PUBLIC_SANITY_PROJECT_ID && process.env.NEXT_PUBLIC_SANITY_PROJECT_ID.length > 0
    ? process.env.NEXT_PUBLIC_SANITY_PROJECT_ID
    : "placeholder";
const dataset =
  process.env.NEXT_PUBLIC_SANITY_DATASET && process.env.NEXT_PUBLIC_SANITY_DATASET.length > 0
    ? process.env.NEXT_PUBLIC_SANITY_DATASET
    : "production";

const previewSecret = process.env.NEXT_PUBLIC_SANITY_PREVIEW_SECRET ?? "";

/**
 * Resolve a public preview URL for a document. Used by Studio's
 * "Open preview" action so editors can see drafts rendered through
 * Next.js /news/[slug] or /studies/[slug] with draftMode enabled.
 */
function resolvePreviewUrl(docType: string, slug: string | undefined): string | undefined {
  if (!slug) return undefined;
  const base = typeof window !== "undefined" ? window.location.origin : "";
  const path =
    docType === "post"
      ? `/news/${slug}`
      : docType === "study"
        ? `/studies/${slug}`
        : `/${slug}`;
  const params = new URLSearchParams({ secret: previewSecret, slug: path });
  return `${base}/api/preview?${params.toString()}`;
}

export default defineConfig({
  name: "orthoglobe",
  title: "OrthoGlobe Editorial",
  basePath: "/studio",
  projectId,
  dataset,
  schema,
  plugins: [structureTool(), visionTool()],
  document: {
    productionUrl: async (_prev, context) => {
      const { document } = context;
      if (document._type !== "post" && document._type !== "study") return undefined;
      const slug = (document as { slug?: { current?: string } }).slug?.current;
      return resolvePreviewUrl(document._type, slug);
    },
  },
});
