import { NextRequest, NextResponse } from 'next/server'
import { buildLoginUrl, resolvePublicOrigin } from '@/lib/url/appUrl'
import { clearUserSession } from '../../_helpers/session'

export const runtime = 'nodejs'

/**
 * 清除 session cookie 並重定向到登入頁
 * 用於當 session 被踢掉時清除 cookie
 */
export async function GET(request: NextRequest) {
    let redirectPath = request.nextUrl.searchParams.get('redirect')
    if (!redirectPath) {
        const referer = request.headers.get('referer')
        if (referer) {
            try {
                const refererUrl = new URL(referer)
                redirectPath = refererUrl.pathname + refererUrl.search
            } catch {
                redirectPath = '/my/profile'
            }
        } else {
            redirectPath = '/my/profile'
        }
    }
    clearUserSession()
    const origin = resolvePublicOrigin(request)
    const loginHref = buildLoginUrl(redirectPath, origin)
    const loginUrl = loginHref.startsWith('http')
        ? new URL(loginHref)
        : new URL(loginHref, request.url)
    return NextResponse.redirect(loginUrl)
}

