interface DataSource {
  type: 'static' | 'api'
  endpoint?: string
  paramField?: string
  titleField?: string
  descriptionField?: string
  imageField?: string
}

class SeoDataService {
  private cache: Map<string, any> = new Map()
  private cacheTimeout = 5 * 60 * 1000 // 5 минут
  private cacheTimestamps: Map<string, number> = new Map()

  async fetchData(endpoint: string, param: string): Promise<any> {
    const cacheKey = `${endpoint}/${param}`
    const cached = this.cache.get(cacheKey)
    const timestamp = this.cacheTimestamps.get(cacheKey)

    if (cached && timestamp && Date.now() - timestamp < this.cacheTimeout) {
      return cached
    }

    try {
      const response = await fetch(`${endpoint}/${param}`)
      const data = await response.json()

      this.cache.set(cacheKey, data)
      this.cacheTimestamps.set(cacheKey, Date.now())

      return data
    } catch (error) {
      console.error('Error fetching SEO data:', error)
      return null
    }
  }

  extractData(data: any, config: DataSource): Record<string, string> {
    return {
      title: config.titleField ? data[config.titleField] : '',
      description: config.descriptionField ? data[config.descriptionField] : '',
      image: config.imageField ? data[config.imageField] : ''
    }
  }
}

export const seoDataService = new SeoDataService()
