import { $atom, z } from "alepha";

/**
 * Schema for the SSR manifest atom.
 */
export const ssrManifestAtomSchema = z.object({
  /**
   * Base path for assets (from Vite's base config).
   * Used to prefix asset URLs when serving from a subpath.
   * @example "/devtools" or "/"
   */
  base: z.string().optional(),

  /**
   * Preload manifest mapping short keys to source paths.
   * Generated by viteAlephaSsrPreload plugin at build time.
   */
  preload: z.record(z.string(), z.string()).optional(),

  /**
   * Client manifest mapping source files to their output information.
   * Only includes fields actually used for preloading.
   */
  client: z
    .record(
      z.string(),
      z.object({
        file: z.string(),
        isEntry: z.boolean().optional(),
        imports: z.array(z.string()).optional(),
        css: z.array(z.string()).optional(),
      }),
    )
    .optional(),

  /**
   * Dev mode head content.
   * Contains pre-transformed scripts injected by Vite and plugins (React, etc.).
   * Only set in dev mode via ViteDevServerProvider.
   */
  devHead: z.string().optional(),

  /**
   * Auto-detected favicon path and MIME type.
   * Format: "type:path" (e.g., "image/svg+xml:/favicon.svg").
   * Set at build/dev time by scanning the public directory.
   */
  favicon: z.string().optional(),
});

/**
 * Type for the SSR manifest schema.
 */
export type SsrManifestAtomSchema = typeof ssrManifestAtomSchema;

/**
 * SSR Manifest atom containing all manifest data for SSR module preloading.
 *
 * This atom is populated at build time by embedding manifest data into the
 * generated index.js. This approach is optimal for serverless deployments
 * as it eliminates filesystem reads at runtime.
 *
 * The manifest includes:
 * - preload: Maps short hash keys to source paths (from viteAlephaSsrPreload)
 * - client: Maps source files to their output info (file, imports, css)
 */
export const ssrManifestAtom = $atom({
  name: "alepha.react.ssr.manifest",
  description: "SSR manifest for module preloading",
  schema: ssrManifestAtomSchema,
  default: {},
});
