import { NextRequest, NextResponse } from 'next/server'
import { headers } from 'next/headers'
import { buildEmbedUrl } from '@/lib/embed/buildEmbedUrl'
import { getAppOriginFromEnv, getAppOriginFromHeaders } from '@/lib/url/appUrl'
import { loadRoomPlaybackData } from '@/lib/room/loadRoomPlaybackData'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

/** oEmbed 發現（類 YouTube）：?url=https://live.../room/{id} */
export async function GET(request: NextRequest) {
    const urlParam = request.nextUrl.searchParams.get('url')?.trim()
    if (!urlParam) {
        return NextResponse.json({ error: 'url is required' }, { status: 400 })
    }

    let parsed: URL
    try {
        parsed = new URL(urlParam)
    } catch {
        return NextResponse.json({ error: 'invalid url' }, { status: 400 })
    }

    const roomMatch = parsed.pathname.match(/^\/room\/([^/]+)\/?$/)
    const embedStreamMatch = parsed.pathname.match(/^\/embed\/stream\/([^/]+)\/?$/)
    const roomIdParam = decodeURIComponent(roomMatch?.[1] ?? embedStreamMatch?.[1] ?? '').trim()
    if (!roomIdParam) {
        return NextResponse.json({ error: 'unsupported url' }, { status: 404 })
    }

    const loaded = await loadRoomPlaybackData(roomIdParam)
    if (!loaded) {
        return NextResponse.json({ error: 'not found' }, { status: 404 })
    }

    const h = headers()
    const origin = getAppOriginFromEnv() || getAppOriginFromHeaders(h) || parsed.origin
    const embedUrl = buildEmbedUrl(origin, loaded.publicRoomId)
    const maxwidth = Math.min(1920, Math.max(200, Number(request.nextUrl.searchParams.get('maxwidth')) || 560))
    const maxheight = Math.min(1080, Math.max(150, Number(request.nextUrl.searchParams.get('maxheight')) || 315))
    const title = loaded.stream.title?.trim()
        ? `${loaded.stream.channelName} — ${loaded.stream.title}`
        : loaded.stream.channelName

    return NextResponse.json({
        type: 'video',
        version: '1.0',
        provider_name: 'NoiR',
        provider_url: origin,
        title,
        author_name: loaded.stream.channelName,
        width: maxwidth,
        height: maxheight,
        html: `<iframe src="${embedUrl}" width="${maxwidth}" height="${maxheight}" frameborder="0" allowfullscreen allow="autoplay; fullscreen; picture-in-picture" title="${title.replace(/"/g, '&quot;')}"></iframe>`,
    })
}
