// middleware.ts
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"
import { getToken } from "next-auth/jwt"

export async function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl
  
  // Rotas públicas
  const publicRoutes = ["/", "/login", "/about", "/api/auth", "/test.html"]
  const isPublicRoute = publicRoutes.some(route => pathname.startsWith(route))
  
  if (isPublicRoute) {
    return NextResponse.next()
  }
  
  // Verificar autenticação
  const token = await getToken({ 
    req, 
    secret: process.env.NEXTAUTH_SECRET 
  })
  
  // Requer autenticação
  if (!token) {
    const loginUrl = new URL("/login", req.url)
    loginUrl.searchParams.set("callbackUrl", pathname)
    return NextResponse.redirect(loginUrl)
  }
  
  // Proteção de workspace
  if (pathname.startsWith("/workspace/")) {
    const slug = pathname.split("/")[2]
    
    if (slug && token.workspaces) {
      const workspaces = token.workspaces as any
      const allWorkspaces = [
        ...(workspaces.asEmployee || []),
        ...(workspaces.asManager || [])
      ]
      
      const hasAccess = allWorkspaces.some((w: any) => w.slug === slug)
      
      if (!hasAccess) {
        return NextResponse.redirect(new URL("/unauthorized", req.url))
      }
    }
  }
  
  return NextResponse.next()
}

export const config = {
  matcher: [
    "/((?!api/auth|_next/static|_next/image|favicon.ico|public).*)"
  ]
}

