import type { MetadataRoute } from 'next'
import { serverGet } from '@/lib/api'
import type { Category, Product, Gym, Paginated } from '@/lib/types'
import { getPosts } from './blog/blog-data'

type IdRow = { id: number }

const SITE = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'

async function safe<T>(p: Promise<T>, fallback: T): Promise<T> {
  try { return await p } catch { return fallback }
}

function unwrap<T>(r: { data?: T[] } | T[]): T[] {
  return (r as { data?: T[] }).data ?? (r as T[])
}

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const now = new Date()

  const staticRoutes: MetadataRoute.Sitemap = [
    '', '/categories', '/gyms', '/providers', '/labs', '/plans', '/about', '/how-it-works', '/blog',
  ].map((path) => ({
    url: `${SITE}${path}`,
    lastModified: now,
    changeFrequency: path === '' ? 'daily' : 'weekly',
    priority: path === '' ? 1 : 0.7,
  }))

  const [cats, products, gyms, providers] = await Promise.all([
    safe(serverGet<{ data: Category[] } | Category[]>('/categories', 3600), []),
    safe(serverGet<Paginated<Product>>('/products?per_page=200', 3600), { data: [] } as Paginated<Product>),
    safe(serverGet<{ data: Gym[] } | Gym[]>('/gyms', 3600), []),
    safe(serverGet<Paginated<IdRow>>('/providers', 3600), { data: [] } as Paginated<IdRow>),
  ])

  const flatCats: Category[] = []
  const walk = (list: Category[]) => list.forEach((c) => { flatCats.push(c); if (c.children?.length) walk(c.children) })
  walk(unwrap<Category>(cats))

  const catRoutes: MetadataRoute.Sitemap = flatCats
    .filter((c) => c.slug)
    .map((c) => ({ url: `${SITE}/category/${c.slug}`, lastModified: now, changeFrequency: 'weekly', priority: 0.6 }))

  const productRoutes: MetadataRoute.Sitemap = (products.data ?? [])
    .map((p) => ({ url: `${SITE}/product/${p.id}`, lastModified: now, changeFrequency: 'weekly', priority: 0.5 }))

  const gymRoutes: MetadataRoute.Sitemap = unwrap<Gym>(gyms)
    .map((g) => ({ url: `${SITE}/gyms/${g.id}`, lastModified: now, changeFrequency: 'weekly', priority: 0.5 }))

  const providerRoutes: MetadataRoute.Sitemap = (providers.data ?? [])
    .map((p) => ({ url: `${SITE}/providers/${p.id}`, lastModified: now, changeFrequency: 'weekly', priority: 0.5 }))

  const posts = await safe(getPosts(), [])
  const blogRoutes: MetadataRoute.Sitemap = posts
    .map((post) => ({ url: `${SITE}/blog/${post.slug}`, lastModified: new Date(post.date), changeFrequency: 'monthly' as const, priority: 0.4 }))

  return [...staticRoutes, ...catRoutes, ...productRoutes, ...gymRoutes, ...providerRoutes, ...blogRoutes]
}
