import { defineEventHandler } from 'h3'

const API_BASE = 'https://new.khalejauto.sa/api'

// Slugify function to match frontend
function slugify(text: string): string {
  if (!text) return ''
  return text
    .toString()
    .toLowerCase()
    .trim()
    .replace(/\s+/g, '-')
    .replace(/[؟,،!%&]/g, '')
    .replace(/-+/g, '-')
}

export default defineEventHandler(async () => {
  const urls: Array<{
    loc: string
    lastmod?: string
    changefreq?: string
    priority?: number
    _sitemap?: string
  }> = []

  try {
    // Fetch cars
    const carsResponse = await fetch(`${API_BASE}/cars`, {
      headers: { 'Content-Language': 'ar' }
    })
    if (carsResponse.ok) {
      const carsData = await carsResponse.json()
      const cars = carsData.data || []

      for (const car of cars) {
        const slug = car.slug_ar || slugify(car.name || car.title)
        const lastmod = car.updated_at || new Date().toISOString()

        if (slug) {
          // Arabic version
          urls.push({
            loc: `/cars/${slug}`,
            lastmod,
            changefreq: 'weekly',
            priority: 0.8,
            _sitemap: 'ar',
          })
          // English version
          urls.push({
            loc: `/en/cars/${slug}`,
            lastmod,
            changefreq: 'weekly',
            priority: 0.8,
            _sitemap: 'en',
          })
        }
      }
    }
  } catch (error) {
    console.error('Error fetching cars for sitemap:', error)
  }

  try {
    // Fetch offers
    const offersResponse = await fetch(`${API_BASE}/offers`, {
      headers: { 'Content-Language': 'ar' }
    })
    if (offersResponse.ok) {
      const offersData = await offersResponse.json()
      const offers = offersData.data || []

      for (const offer of offers) {
        const slug = slugify(offer.title)
        const lastmod = offer.updated_at || new Date().toISOString()

        if (slug) {
          // Arabic version
          urls.push({
            loc: `/offers/${slug}`,
            lastmod,
            changefreq: 'weekly',
            priority: 0.8,
            _sitemap: 'ar',
          })
          // English version
          urls.push({
            loc: `/en/offers/${slug}`,
            lastmod,
            changefreq: 'weekly',
            priority: 0.8,
            _sitemap: 'en',
          })
        }
      }
    }
  } catch (error) {
    console.error('Error fetching offers for sitemap:', error)
  }

  try {
    // Fetch blogs/news
    const newsResponse = await fetch(`${API_BASE}/news`, {
      headers: { 'Content-Language': 'ar' }
    })
    if (newsResponse.ok) {
      const newsData = await newsResponse.json()
      const newsList = newsData.data || []

      for (const news of newsList) {
        const slug = slugify(news.title)
        const lastmod = news.updated_at || news.created_at || new Date().toISOString()

        if (slug) {
          // Arabic version
          urls.push({
            loc: `/blogs/${slug}`,
            lastmod,
            changefreq: 'weekly',
            priority: 0.7,
            _sitemap: 'ar',
          })
          // English version
          urls.push({
            loc: `/en/blogs/${slug}`,
            lastmod,
            changefreq: 'weekly',
            priority: 0.7,
            _sitemap: 'en',
          })
        }
      }
    }
  } catch (error) {
    console.error('Error fetching news for sitemap:', error)
  }

  try {
    // Fetch services
    const servicesResponse = await fetch(`${API_BASE}/services`, {
      headers: { 'Content-Language': 'ar' }
    })
    if (servicesResponse.ok) {
      const servicesData = await servicesResponse.json()
      const services = servicesData.data || []

      for (const service of services) {
        const slug = slugify(service.title)
        const lastmod = service.updated_at || new Date().toISOString()

        if (slug) {
          // Arabic version
          urls.push({
            loc: `/services/${slug}`,
            lastmod,
            changefreq: 'monthly',
            priority: 0.7,
            _sitemap: 'ar',
          })
          // English version
          urls.push({
            loc: `/en/services/${slug}`,
            lastmod,
            changefreq: 'monthly',
            priority: 0.7,
            _sitemap: 'en',
          })
        }
      }
    }
  } catch (error) {
    console.error('Error fetching services for sitemap:', error)
  }

  return urls
})
