import { NextRequest, NextResponse } from 'next/server'

export async function POST(req: NextRequest){
  const { url } = await req.json()
  if(!url) return NextResponse.json({ error: 'url 필요' }, { status: 400 })
  try {
    const res = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' } })
    const html = await res.text()

    const getMeta = (prop: string) => {
      const regex = new RegExp(`<meta[^>]+property=[\"']${prop}[\"'][^>]*content=[\"']([^\"']+)[\"']`, 'i')
      const match = html.match(regex)
      if(match) return match[1]
      const regex2 = new RegExp(`<meta[^>]+content=[\"']([^\"']+)[\"'][^>]*property=[\"']${prop}[\"']`, 'i')
      const m2 = html.match(regex2)
      return m2 ? m2[1] : null
    }

    const title = getMeta('og:title') || html.match(/<title>([^<]+)<\/title>/i)?.[1] || ''
    const image = getMeta('og:image') || ''
    const desc = getMeta('og:description') || ''

    return NextResponse.json({ title: title.trim(), image, description: desc.trim() })
  } catch(e:any){
    return NextResponse.json({ error: e.message, title: '', image: '' }, { status: 500 })
  }
}
