import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { SESSION_ID_COOKIE } from '@/app/_helpers/constants'
import { buildLoginUrl, resolvePublicOrigin } from '@/lib/url/appUrl'

function requiresAuth(pathname: string): boolean {
    return pathname.startsWith('/my') || pathname === '/room/dashboard'
}

function redirectToLogin(request: NextRequest, pathname: string) {
    const origin = resolvePublicOrigin(request)
    const loginHref = buildLoginUrl(pathname, origin)
    const loginUrl = loginHref.startsWith('http')
        ? new URL(loginHref)
        : new URL(loginHref, request.url)
    return NextResponse.redirect(loginUrl)
}

export function middleware(request: NextRequest) {
    const { pathname } = request.nextUrl
    if (!requiresAuth(pathname)) {
        return NextResponse.next()
    }

    const sessionId = request.cookies.get(SESSION_ID_COOKIE)?.value
    if (!sessionId) {
        return redirectToLogin(request, pathname)
    }

    return NextResponse.next()
}

export const config = {
    matcher: ['/my', '/my/:path*', '/room/dashboard'],
}

