import { EVENTS } from '@/constants/events'

/**
 * 事件属性验证器
 * 确保事件属性符合预定义规范
 */

// 事件属性Schema定义
const eventSchemas = {
  [EVENTS.NEWS_VIEWED]: {
    required: ['news_id', 'news_title'],
    optional: ['news_category', 'reading_duration', 'entry_source'],
    types: {
      news_id: 'string',
      news_title: 'string',
      news_category: 'string',
      reading_duration: 'number',
      entry_source: 'string',
    },
  },

  [EVENTS.SEARCH_EXECUTED]: {
    required: ['search_query'],
    optional: ['search_type', 'result_count', 'search_time'],
    types: {
      search_query: 'string',
      search_type: 'string',
      result_count: 'number',
      search_time: 'number',
    },
  },

  [EVENTS.CONTENT_FAVORITED]: {
    required: ['content_id', 'content_type'],
    optional: ['content_title', 'content_category'],
    types: {
      content_id: 'string',
      content_type: 'string',
      content_title: 'string',
      content_category: 'string',
    },
  },

  [EVENTS.API_ERROR]: {
    required: ['api_path', 'error_code', 'error_message'],
    optional: ['api_method', 'request_duration'],
    types: {
      api_path: 'string',
      api_method: 'string',
      error_code: ['number', 'string'],
      error_message: 'string',
      request_duration: 'number',
    },
  },
}

/**
 * 验证事件属性
 * @param {string} eventName - 事件名称
 * @param {object} properties - 事件属性
 * @returns {object} - { valid: boolean, errors: string[] }
 */
export function validateEventProperties(eventName, properties) {
  const schema = eventSchemas[eventName]

  // 没有定义schema的事件，跳过验证
  if (!schema) {
    return { valid: true, errors: [] }
  }

  const errors = []

  // 检查必需属性
  for (const field of schema.required || []) {
    if (!(field in properties)) {
      errors.push(`Missing required property: ${field}`)
    }
  }

  // 检查属性类型
  for (const [field, value] of Object.entries(properties)) {
    const expectedType = schema.types?.[field]
    if (expectedType) {
      const actualType = typeof value
      const validTypes = Array.isArray(expectedType) ? expectedType : [expectedType]

      if (!validTypes.includes(actualType)) {
        errors.push(`Invalid type for ${field}: expected ${validTypes.join(' or ')}, got ${actualType}`)
      }
    }
  }

  return {
    valid: errors.length === 0,
    errors,
  }
}

/**
 * 验证并警告（开发模式使用）
 */
export function validateAndWarn(eventName, properties, debug = false) {
  if (!debug) return

  const result = validateEventProperties(eventName, properties)
  if (!result.valid) {
    console.warn(`[PostHog Validator] Event "${eventName}" validation failed:`, result.errors)
  }
}

export default {
  validateEventProperties,
  validateAndWarn,
}