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

function isProtectedRoute(req: NextRequest) {
  return req.nextUrl.pathname === '/dashboard' || req.nextUrl.pathname.startsWith('/dashboard/')
}

function localJwtMiddleware(req: NextRequest): NextResponse {
  if (!isProtectedRoute(req)) return NextResponse.next()

  // Check for employee_token cookie (set on login) OR allow if coming from sign-in
  const token = req.cookies.get('employee_token')?.value
  if (!token) {
    const signInUrl = new URL('/sign-in', req.url)
    signInUrl.searchParams.set('redirect', req.nextUrl.pathname)
    return NextResponse.redirect(signInUrl)
  }
  return NextResponse.next()
}

export default function middleware(req: NextRequest) {
  return localJwtMiddleware(req)
}

export const config = {
  matcher: [
    '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    '/(api|trpc)(.*)',
  ],
}
