import type { AppliedDataSemantic } from '../Semantics.js'
import { SemanticType } from '../Semantics.js'

/**
 * Configuration options for the PublicUniqueName (slug) semantic.
 * Controls how slugs are generated and validated.
 */
export interface PublicUniqueNameConfig {
  /**
   * The key of the source field to generate the slug from.
   * Default to the field that is annotated with the Title semantic.
   */
  sourceField?: string
  /**
   * Separator character to use in the slug (default: '-').
   */
  separator?: string
  /**
   * Whether the slug is case sensitive (default: false).
   */
  caseSensitive?: boolean
  /**
   * Whether to allow Unicode characters in the slug (default: false).
   */
  allowUnicode?: boolean
  /**
   * Whether to allow duplicate slugs (default: false).
   */
  allowDuplicates?: boolean
  /**
   * Fallback field to use if the source field is empty or invalid.
   */
  fallbackField?: string
  /**
   * Custom metadata for the slug field.
   */
  metadata?: Record<string, unknown>
  /**
   * Index signature to allow additional properties.
   */
  [key: string]: unknown
}

/**
 * Type-safe configuration for PublicUniqueName semantic.
 */
export interface AppliedPublicUniqueNameSemantic extends AppliedDataSemantic {
  id: SemanticType.PublicUniqueName
  config?: PublicUniqueNameConfig
}

/**
 * Type guard to check if a semantic is a PublicUniqueName semantic.
 */
export const isPublicUniqueNameSemantic = (
  semantic: AppliedDataSemantic
): semantic is AppliedPublicUniqueNameSemantic => {
  return semantic.id === SemanticType.PublicUniqueName
}

/**
 * Helper function to create a PublicUniqueName semantic with configuration.
 */
export const createPublicUniqueNameSemantic = (
  config: PublicUniqueNameConfig = {}
): AppliedPublicUniqueNameSemantic => {
  const mergedConfig = {
    ...DEFAULT_PUBLIC_UNIQUE_NAME_CONFIG,
    ...config,
  }
  if (config.metadata) {
    mergedConfig.metadata = { ...config.metadata }
  }

  return {
    id: SemanticType.PublicUniqueName,
    config: mergedConfig,
  }
}

/**
 * Default configuration for PublicUniqueName semantic.
 */
export const DEFAULT_PUBLIC_UNIQUE_NAME_CONFIG: PublicUniqueNameConfig = {
  separator: '-',
  caseSensitive: false,
  allowUnicode: false,
  allowDuplicates: false,
}
