import {
  SYSTEM_BLOCK_KINDS
} from "./chunk-D2QLTPUJ.mjs";
import {
  SUPPORTED_LOADER_ENDPOINTS
} from "./chunk-7DS4Q3GA.mjs";
import {
  blockCategoryEnum,
  fieldSchema,
  getBlockDefinition
} from "./chunk-USQF2XTU.mjs";

// src/config/validation.ts
import { z as z2 } from "zod";

// src/config/content-validation.ts
import { z } from "zod";
var jsonDataSchema = z.record(z.string(), z.any());
var contentTypeKeySchema = z.string().min(1).regex(
  /^[a-z][a-z0-9-]*$/,
  "Key must be lowercase, start with a letter, and contain only letters, numbers, and hyphens"
);
var contentTypeConfigSchema = z.object({
  key: contentTypeKeySchema,
  name: z.string().min(1),
  description: z.string().optional(),
  hasPages: z.boolean(),
  routePattern: z.string().optional(),
  // Fields are validated as any[] here - deep field validation happens in @riverbankcms/blocks
  fields: z.array(z.any()).min(1, "At least one field is required"),
  titleField: z.string().optional()
}).refine(
  (data) => {
    if (data.hasPages) {
      return data.routePattern && data.routePattern.includes("{slug}");
    }
    return true;
  },
  { message: "routePattern with {slug} is required when hasPages is true" }
).refine(
  (data) => {
    if (!data.hasPages && data.routePattern) {
      return false;
    }
    return true;
  },
  { message: "routePattern must not be defined when hasPages is false" }
);
var blockKindSchema = z.string().refine(
  (kind) => {
    if (SYSTEM_BLOCK_KINDS.includes(kind)) {
      return true;
    }
    if (kind.startsWith("custom.") && kind.length > 7) {
      return true;
    }
    return false;
  },
  {
    message: 'Block kind must be a system block (e.g., "block.hero") or a custom block (e.g., "custom.myBlock")'
  }
);
var blockConfigSchema = z.object({
  kind: blockKindSchema,
  content: jsonDataSchema,
  orderIndex: z.number().optional()
});
var pageConfigSchema = z.object({
  identifier: z.string().min(1, "Identifier is required"),
  title: z.string().min(1, "Title is required"),
  path: z.string().regex(/^\//, "Path must start with /"),
  purpose: z.string().default("content"),
  blocks: z.array(blockConfigSchema).optional(),
  status: z.enum(["draft", "published"]).default("draft"),
  metaTitle: z.string().optional(),
  metaDescription: z.string().optional()
});
var entryConfigSchema = z.object({
  identifier: z.string().min(1, "Identifier is required"),
  contentType: z.string().min(1, "Content type is required"),
  data: jsonDataSchema,
  status: z.enum(["draft", "published"]).default("draft"),
  slug: z.string().optional(),
  title: z.string().optional(),
  summary: z.string().optional(),
  metaTitle: z.string().optional(),
  metaDescription: z.string().optional()
});
var pageLinkSchema = z.object({
  kind: z.literal("page"),
  identifier: z.string().min(1)
});
var entryLinkSchema = z.object({
  kind: z.literal("entry"),
  identifier: z.string().min(1)
});
var externalLinkSchema = z.object({
  kind: z.literal("external"),
  href: z.string().url("Invalid URL")
});
var dropdownLinkSchema = z.object({
  kind: z.literal("dropdown")
});
var navigationLinkSchema = z.discriminatedUnion("kind", [
  pageLinkSchema,
  entryLinkSchema,
  externalLinkSchema,
  dropdownLinkSchema
]);
var baseNavigationItemSchema = z.object({
  label: z.string().min(1, "Label is required"),
  link: navigationLinkSchema,
  isCta: z.boolean().optional()
});
var navigationItemConfigSchema = baseNavigationItemSchema.extend({
  children: z.lazy(() => z.array(navigationItemConfigSchema)).optional()
});
var navigationMenuConfigSchema = z.object({
  identifier: z.string().min(1, "Identifier is required"),
  name: z.string().min(1, "Name is required"),
  isPrimary: z.boolean().optional(),
  items: z.array(navigationItemConfigSchema)
});
var siteSettingsConfigSchema = z.object({
  homepagePath: z.string().optional(),
  siteTitle: z.string().optional(),
  siteDescription: z.string().optional(),
  defaultTemplates: z.record(z.string(), z.string()).optional()
});
var contentConfigBaseSchema = z.object({
  contentTypes: z.array(contentTypeConfigSchema).optional(),
  entries: z.array(entryConfigSchema).optional(),
  pages: z.array(pageConfigSchema).optional(),
  navigationMenus: z.array(navigationMenuConfigSchema).optional(),
  settings: siteSettingsConfigSchema.optional()
});
var contentConfigSchema = contentConfigBaseSchema.superRefine((data, ctx) => {
  if (data.contentTypes && data.contentTypes.length > 1) {
    const keys = data.contentTypes.map((ct) => ct.key);
    const duplicateKeys = keys.filter((key, i) => keys.indexOf(key) !== i);
    if (duplicateKeys.length > 0) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: `Content type keys must be unique. Duplicates: ${duplicateKeys.join(", ")}`,
        path: ["contentTypes"]
      });
    }
  }
  if (data.pages && data.pages.length > 1) {
    const identifiers = data.pages.map((p) => p.identifier);
    const duplicateIds = identifiers.filter((id, i) => identifiers.indexOf(id) !== i);
    if (duplicateIds.length > 0) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: `Page identifiers must be unique. Duplicates: ${duplicateIds.join(", ")}`,
        path: ["pages"]
      });
    }
    const paths = data.pages.map((p) => p.path);
    const duplicatePaths = paths.filter((path, i) => paths.indexOf(path) !== i);
    if (duplicatePaths.length > 0) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: `Page paths must be unique. Duplicates: ${duplicatePaths.join(", ")}`,
        path: ["pages"]
      });
    }
  }
  if (data.entries && data.entries.length > 1) {
    const identifiers = data.entries.map((e) => e.identifier);
    const duplicateIds = identifiers.filter((id, i) => identifiers.indexOf(id) !== i);
    if (duplicateIds.length > 0) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: `Entry identifiers must be unique. Duplicates: ${duplicateIds.join(", ")}`,
        path: ["entries"]
      });
    }
  }
  if (data.navigationMenus && data.navigationMenus.length > 1) {
    const identifiers = data.navigationMenus.map((m) => m.identifier);
    const duplicateIds = identifiers.filter((id, i) => identifiers.indexOf(id) !== i);
    if (duplicateIds.length > 0) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: `Navigation menu identifiers must be unique. Duplicates: ${duplicateIds.join(", ")}`,
        path: ["navigationMenus"]
      });
    }
  }
});

// src/config/validation.ts
var sdkThemePaletteSchema = z2.record(z2.string(), z2.string());
var sdkThemeConfigSchema = z2.object({
  palette: sdkThemePaletteSchema
});
var sectionBackgroundSchema = z2.object({
  id: z2.string(),
  label: z2.string(),
  token: z2.string()
  // Reference to theme palette token
});
var sectionSpacingSchema = z2.enum(["compact", "default", "spacious"]);
var containerMaxWidthSchema = z2.enum(["narrow", "default", "wide", "full"]);
var containerAlignmentSchema = z2.enum(["left", "center", "right"]);
var sectionOptionsSchema = z2.object({
  backgroundColor: z2.boolean().optional(),
  backgroundImage: z2.boolean().optional(),
  backgroundGradient: z2.boolean().optional(),
  spacing: z2.union([
    z2.array(sectionSpacingSchema),
    z2.boolean()
  ]).optional(),
  textColor: z2.boolean().optional()
}).optional();
var containerOptionsSchema = z2.object({
  maxWidth: z2.union([
    z2.array(containerMaxWidthSchema),
    z2.boolean()
  ]).optional(),
  alignment: z2.union([
    z2.array(containerAlignmentSchema),
    z2.boolean()
  ]).optional()
}).optional();
var siteStyleConfigSchema = z2.object({
  sectionBackgrounds: z2.array(sectionBackgroundSchema).optional(),
  sectionOptions: sectionOptionsSchema,
  containerOptions: containerOptionsSchema
}).optional();
var sdkLoaderEndpointSchema = z2.enum(SUPPORTED_LOADER_ENDPOINTS);
var loaderParamBindingSchema = z2.object({
  $bind: z2.object({
    from: z2.string().min(1, "Binding path is required"),
    fallback: z2.string().optional()
  })
});
var loaderParamValueSchema = z2.union([
  z2.string(),
  z2.number(),
  z2.boolean(),
  loaderParamBindingSchema
]);
var sdkConfigLoaderSchema = z2.object({
  endpoint: sdkLoaderEndpointSchema,
  params: z2.record(z2.string(), loaderParamValueSchema),
  mode: z2.enum(["server", "client"]).default("server")
});
var sdkDataLoadersSchema = z2.record(z2.string(), sdkConfigLoaderSchema).refine(
  (loaders) => Object.keys(loaders).length <= 5,
  { message: "Maximum 5 data loaders per block" }
).optional();
var fieldSelectOptionSchema = z2.object({
  value: z2.string().min(1, "Option value is required"),
  label: z2.string().min(1, "Option label is required")
});
var blockFieldConfigSchema = z2.object({
  options: z2.array(fieldSelectOptionSchema).min(1, "At least one option is required").optional()
});
var blockFieldOptionsSchema = z2.record(
  z2.string().regex(/^(block\.|custom\.)[a-z][a-z0-9-]*$/, {
    message: "Block ID must be 'block.*' or 'custom.*' format"
  }),
  z2.record(
    z2.string().min(1, "Field ID is required"),
    blockFieldConfigSchema
  )
).optional();
var blockFieldExtensionSchema = z2.object({
  fields: fieldSchema.array().min(1, "At least one field is required")
}).refine(
  (data) => {
    return data.fields.every((field) => {
      if (!field.required) return true;
      return field.defaultValue !== void 0;
    });
  },
  {
    message: "Required fields must have a defaultValue to support existing blocks"
  }
);
var blockFieldExtensionsSchema = z2.record(
  z2.string().regex(/^block\.[a-z][a-zA-Z0-9]*$/, {
    message: "Block ID must be 'block.*' format (system blocks only)"
  }),
  blockFieldExtensionSchema
).optional();
function validateFieldIdConflicts(blockFieldExtensions) {
  if (!blockFieldExtensions) return [];
  const conflicts = [];
  for (const [blockId, extension] of Object.entries(blockFieldExtensions)) {
    const definition = getBlockDefinition(blockId);
    if (!definition) {
      conflicts.push({
        blockId,
        fieldId: "",
        message: `Unknown block type: ${blockId}`
      });
      continue;
    }
    const existingFieldIds = /* @__PURE__ */ new Set();
    const collectFieldIds = (fields) => {
      if (!fields) return;
      for (const field of fields) {
        existingFieldIds.add(field.id);
        if (field.type === "group" || field.type === "modal") {
          collectFieldIds(field.schema?.fields);
        } else if (field.type === "repeater" && field.schema?.fields) {
          collectFieldIds(field.schema.fields);
        } else if (field.type === "tabGroup") {
          for (const tab of field.tabs ?? []) {
            collectFieldIds(tab.fields);
          }
        }
      }
    };
    collectFieldIds(definition.manifest.fields);
    for (const field of extension.fields) {
      if (existingFieldIds.has(field.id)) {
        conflicts.push({
          blockId,
          fieldId: field.id,
          message: `Field ID "${field.id}" conflicts with existing field in ${blockId}`
        });
      }
    }
  }
  return conflicts;
}
var sdkCustomBlockSchema = z2.object({
  // Block ID must start with 'custom.'
  id: z2.string().min(8).regex(/^custom\.[a-z][a-z0-9-]*$/, {
    message: "Block ID must start with 'custom.' followed by lowercase letters, numbers, or hyphens"
  }),
  title: z2.string().min(1, "Title is required"),
  titleSource: z2.string().optional(),
  description: z2.string().optional(),
  category: blockCategoryEnum,
  icon: z2.string().optional(),
  tags: z2.array(z2.string()).optional(),
  // Reuse the exact field schema from @riverbankcms/blocks - all field types supported
  fields: fieldSchema.array().min(1, "Custom blocks must have at least one field"),
  // Data loaders for CMS endpoints
  dataLoaders: sdkDataLoadersSchema
}).refine(
  // Validate titleSource references a valid field if provided
  (data) => {
    if (!data.titleSource) return true;
    return data.fields.some((f) => f.id === data.titleSource);
  },
  {
    message: "titleSource must reference a valid field ID",
    path: ["titleSource"]
  }
);
var riverbankSiteConfigSchema = z2.object({
  siteId: z2.string().uuid(),
  theme: sdkThemeConfigSchema.optional(),
  styles: siteStyleConfigSchema,
  customBlocks: z2.array(sdkCustomBlockSchema).max(20, "Maximum 20 custom blocks per site").refine(
    // Ensure unique block IDs
    (blocks) => {
      const ids = blocks.map((b) => b.id);
      return ids.length === new Set(ids).size;
    },
    { message: "Block IDs must be unique" }
  ).optional(),
  blockFieldOptions: blockFieldOptionsSchema,
  blockFieldExtensions: blockFieldExtensionsSchema,
  content: contentConfigSchema.optional()
}).strict();

export {
  contentTypeConfigSchema,
  blockConfigSchema,
  pageConfigSchema,
  entryConfigSchema,
  navigationItemConfigSchema,
  navigationMenuConfigSchema,
  siteSettingsConfigSchema,
  contentConfigSchema,
  sdkThemePaletteSchema,
  sdkThemeConfigSchema,
  sectionBackgroundSchema,
  sectionSpacingSchema,
  containerMaxWidthSchema,
  containerAlignmentSchema,
  sectionOptionsSchema,
  containerOptionsSchema,
  siteStyleConfigSchema,
  sdkLoaderEndpointSchema,
  loaderParamBindingSchema,
  loaderParamValueSchema,
  sdkConfigLoaderSchema,
  sdkDataLoadersSchema,
  fieldSelectOptionSchema,
  blockFieldConfigSchema,
  blockFieldOptionsSchema,
  blockFieldExtensionSchema,
  blockFieldExtensionsSchema,
  validateFieldIdConflicts,
  sdkCustomBlockSchema,
  riverbankSiteConfigSchema
};
//# sourceMappingURL=chunk-BOHTTHY5.mjs.map