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

/**
 * Configuration options for the Calculated semantic.
 * Controls formula, dependencies, and recalculation behavior.
 *
 * Use Calculated when you need mathematical operations, aggregations, or complex business logic.
 */
export interface CalculatedConfig {
  /**
   * Formula to calculate the value (e.g., 'price * quantity').
   */
  formula: string
  /**
   * List of field names this calculation depends on.
   */
  dependencies?: string[]
  /**
   * Whether to recalculate the value on update (default: true).
   */
  recalculateOnUpdate?: boolean
  /**
   * Whether to allow manual override of the calculated value.
   */
  allowManualOverride?: boolean
  /**
   * Custom metadata for the calculated field.
   */
  metadata?: Record<string, unknown>
  /**
   * Index signature to allow additional properties.
   */
  [key: string]: unknown
}

/**
 * Type-safe configuration for Calculated semantic.
 */
export interface AppliedCalculatedSemantic extends AppliedDataSemantic {
  id: SemanticType.Calculated
  config?: CalculatedConfig
}

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

/**
 * Helper function to create a Calculated semantic with configuration.
 */
export const createCalculatedSemantic = (config: CalculatedConfig): AppliedCalculatedSemantic => {
  const mergedConfig = {
    ...DEFAULT_CALCULATED_CONFIG,
    ...config,
  }
  if (config.metadata) {
    mergedConfig.metadata = { ...config.metadata }
  }

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

/**
 * Default configuration for Calculated semantic.
 */
export const DEFAULT_CALCULATED_CONFIG: Partial<CalculatedConfig> = {
  recalculateOnUpdate: true,
  allowManualOverride: false,
}
