import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import Script from 'next/script'
import { SITE_URL } from '@/lib/seo'
import BuyDomainClient from './BuyDomainClient'
import type { Listing } from './types'

async function fetchListing(slug: string): Promise<Listing | null> {
  try {
    // Build API URL correctly:
    // - BACKEND_URL is just the host (e.g. http://127.0.0.1:8000)
    // - NEXT_PUBLIC_API_URL already includes /api/v1 (e.g. https://pounce.ch/api/v1)
    // - SITE_URL is just the frontend host (e.g. https://pounce.ch)
    let apiUrl: string
    
    if (process.env.BACKEND_URL) {
      // Internal backend URL (no /api/v1 suffix)
      apiUrl = `${process.env.BACKEND_URL.replace(/\/$/, '')}/api/v1/listings/${encodeURIComponent(slug)}`
    } else if (process.env.NEXT_PUBLIC_API_URL) {
      // Already includes /api/v1
      apiUrl = `${process.env.NEXT_PUBLIC_API_URL.replace(/\/$/, '')}/listings/${encodeURIComponent(slug)}`
    } else {
      // Fallback to site URL
      apiUrl = `${SITE_URL.replace(/\/$/, '')}/api/v1/listings/${encodeURIComponent(slug)}`
    }
    
    const res = await fetch(apiUrl, {
      next: { revalidate: 60 },
      headers: {
        'Accept': 'application/json',
      },
    })
    
    if (res.status === 404) return null
    if (!res.ok) {
      console.error(`[fetchListing] Failed to load listing ${slug}: ${res.status} from ${apiUrl}`)
      return null
    }
    return (await res.json()) as Listing
  } catch (error) {
    console.error(`[fetchListing] Error fetching listing ${slug}:`, error)
    return null
  }
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>
}): Promise<Metadata> {
  const { slug } = await params
  const listing = await fetchListing(slug)
  if (!listing) return { title: 'Listing not found | Pounce', robots: { index: false, follow: false } }

  const title = listing.title ? `${listing.domain} — ${listing.title}` : `${listing.domain} — Verified Domain Listing`
  const description =
    listing.description ||
    `Buy ${listing.domain} via Pounce Direct. DNS-verified seller, clean workflow, and secure transfer.`

  return {
    title,
    description,
    alternates: { canonical: `${SITE_URL}/buy/${listing.slug}` },
    openGraph: {
      title,
      description,
      url: `${SITE_URL}/buy/${listing.slug}`,
      type: 'website',
    },
  }
}

export default async function BuyDomainPage({
  params,
}: {
  params: Promise<{ slug: string }>
}) {
  const { slug } = await params
  const listing = await fetchListing(slug)
  if (!listing) notFound()

  const schema = {
    '@context': 'https://schema.org',
    '@type': 'Product',
    name: listing.domain,
    description: listing.description || listing.title || `Domain ${listing.domain} listed on Pounce Direct.`,
    url: `${SITE_URL}/buy/${listing.slug}`,
    category: 'Domain Names',
    offers: listing.asking_price
      ? {
          '@type': 'Offer',
          price: String(listing.asking_price),
          priceCurrency: listing.currency || 'USD',
          availability: 'https://schema.org/InStock',
          url: `${SITE_URL}/buy/${listing.slug}`,
          seller: {
            '@type': 'Organization',
            name: 'Pounce Direct',
          },
        }
      : undefined,
    additionalProperty: [
      { '@type': 'PropertyValue', name: 'dns_verified', value: listing.is_verified ? 'true' : 'false' },
      { '@type': 'PropertyValue', name: 'price_type', value: listing.price_type },
      { '@type': 'PropertyValue', name: 'allow_offers', value: listing.allow_offers ? 'true' : 'false' },
    ],
  }

  return (
    <>
      <Script id="pounce-buy-schema" type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }} />
      <BuyDomainClient initialListing={listing} />
    </>
  )
}
