import { defineConfig, type InputProps } from 'sanity';
import { structureTool } from 'sanity/structure';
import { visionTool } from '@sanity/vision';
import { structure } from './structure';
import { schemaTypes } from './schemas';

const projectId = process.env.SANITY_STUDIO_PROJECT_ID || 'dm2d002p';
const dataset = process.env.SANITY_STUDIO_DATASET || 'production';
// Where "Open preview" goes. Point it at the preview deployment, which also shows drafts.
const previewUrl = process.env.SANITY_STUDIO_PREVIEW_URL || 'https://www.shanina.co.il';

const PATHS: Record<string, string> = { article: 'articles', recipe: 'recipes', spice: 'spices' };

/** Hebrew text fields and the rich text editor type right-to-left. */
function RtlInput(props: InputProps) {
  const { schemaType } = props;
  const isText = schemaType.jsonType === 'string' && !['url', 'slug', 'datetime', 'date'].includes(schemaType.name);
  const isRichText = schemaType.jsonType === 'array' && (schemaType as any).of?.some((t: any) => t.name === 'block' || t.type?.name === 'block');
  if (!isText && !isRichText) return props.renderDefault(props);
  return <div dir="rtl">{props.renderDefault(props)}</div>;
}

const SINGLETONS = new Set(['siteSettings']);

export default defineConfig({
  name: 'shanina',
  title: 'שנינה – ניהול האתר',
  projectId,
  dataset,
  // '/admin' when served inside the site, '/' on shanina.sanity.studio
  basePath: process.env.SANITY_STUDIO_BASE_PATH || '/',
  plugins: [structureTool({ structure, title: 'תוכן' }), visionTool({ title: 'שאילתות (טכני)' })],
  schema: {
    types: schemaTypes,
    // Settings is a single document: hide it from "create new".
    templates: (templates) => templates.filter(({ schemaType }) => !SINGLETONS.has(schemaType)),
  },
  form: { components: { input: RtlInput } },
  document: {
    actions: (actions, { schemaType }) =>
      SINGLETONS.has(schemaType) ? actions.filter(({ action }) => action && ['publish', 'discardChanges', 'restore'].includes(action)) : actions,
    productionUrl: async (prev, { document }) => {
      const slug = (document as any)?.slug?.current;
      if (document._type === 'page' && slug) return `${previewUrl}/${slug === 'home' ? '' : slug}`;
      if (PATHS[document._type] && slug) return `${previewUrl}/${PATHS[document._type]}/${slug}`;
      return prev;
    },
  },
});
