import { NextResponse } from 'next/server'

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

function getWhepUpstreamOrigin(): string {
    const raw =
        process.env.WHEP_PROXY_UPSTREAM?.trim() ||
        process.env.NEXT_PUBLIC_WHIP_PUBLISH_ORIGIN?.trim() ||
        'https://live.gp777s.com'
    return raw.replace(/\/$/, '')
}

function buildUpstreamUrl(pathSegments: string[]): string {
    const upstream = getWhepUpstreamOrigin()
    const suffix = pathSegments.map((p) => encodeURIComponent(p)).join('/')
    return `${upstream}/webRTC/${suffix}`
}

/** 將上游 Location 改寫為同源 API，避免瀏覽器對 live.gp777s.com 發 DELETE 時再觸發 CORS */
function rewriteLocationForClient(
    location: string | null,
    request: Request,
    pathSegments: string[]
): string | null {
    if (!location?.trim()) return null

    const appOrigin = new URL(request.url).origin
    const upstreamOrigin = getWhepUpstreamOrigin()

    try {
        const resolved = new URL(location, `${upstreamOrigin}/webRTC/`)
        if (resolved.origin === upstreamOrigin || location.startsWith('/')) {
            const path = resolved.pathname.replace(/^\/webRTC\/?/i, '')
            return `${appOrigin}/api/stream/whep/${path}${resolved.search}`
        }
    } catch {
        // fall through
    }

    if (pathSegments.length > 0) {
        return `${appOrigin}/api/stream/whep/${pathSegments.join('/')}`
    }

    return location
}

const WHEP_FORWARD_REQUEST_HEADERS = ['content-type', 'accept', 'authorization', 'if-match'] as const

const WHEP_FORWARD_RESPONSE_HEADERS = [
    'content-type',
    'location',
    'link',
    'etag',
    'accept-post',
    'accept-patch',
] as const

async function proxyToUpstream(
    request: Request,
    pathSegments: string[],
    method: 'POST' | 'DELETE'
) {
    const upstreamUrl = buildUpstreamUrl(pathSegments)

    const headers: HeadersInit = {}
    for (const name of WHEP_FORWARD_REQUEST_HEADERS) {
        const value = request.headers.get(name)
        if (value) headers[name] = value
    }

    const init: RequestInit = { method, headers }
    if (method === 'POST') {
        init.body = await request.text()
    }

    const upstream = await fetch(upstreamUrl, init)
    const body = await upstream.text()

    const outHeaders = new Headers()
    for (const name of WHEP_FORWARD_RESPONSE_HEADERS) {
        const value = upstream.headers.get(name)
        if (value) outHeaders.set(name, value)
    }

    const location = rewriteLocationForClient(
        upstream.headers.get('location'),
        request,
        pathSegments
    )
    if (location) {
        outHeaders.set('Location', location)
    }

    return new NextResponse(body, {
        status: upstream.status,
        headers: outHeaders,
    })
}

export async function OPTIONS() {
    return new NextResponse(null, {
        status: 204,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'OPTIONS, POST, DELETE',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization, If-Match, ETag, Accept, Link',
            'Access-Control-Expose-Headers': 'Location, Link, ETag, Accept-Post, Accept-Patch',
        },
    })
}

export async function POST(
    request: Request,
    context: { params: { path?: string[] } }
) {
    const pathSegments = context.params.path ?? []
    if (pathSegments.length === 0) {
        return NextResponse.json({ error: 'Missing WHEP path' }, { status: 400 })
    }
    try {
        return await proxyToUpstream(request, pathSegments, 'POST')
    } catch (error) {
        console.error('[whep-proxy] POST failed:', error)
        return NextResponse.json({ error: 'WHEP proxy failed' }, { status: 502 })
    }
}

export async function DELETE(
    request: Request,
    context: { params: { path?: string[] } }
) {
    const pathSegments = context.params.path ?? []
    if (pathSegments.length === 0) {
        return NextResponse.json({ error: 'Missing WHEP path' }, { status: 400 })
    }
    try {
        return await proxyToUpstream(request, pathSegments, 'DELETE')
    } catch (error) {
        console.error('[whep-proxy] DELETE failed:', error)
        return NextResponse.json({ error: 'WHEP proxy failed' }, { status: 502 })
    }
}
