import { cookies } from 'next/headers'
import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"

const protectedRoutes = ["/"]
const publicRoutes = ["/entrada"]

export default async function middleware(request: NextRequest) {
	const pathname = request.nextUrl.pathname
	const res = NextResponse.next()
	
	// Ignora arquivos estáticos e APIs
	if (
		pathname.startsWith('/_next/') ||
		pathname.startsWith('/static/') ||
		pathname.endsWith('.css') ||
		pathname.endsWith('.js') ||
		pathname.endsWith('.ico') ||
		pathname.endsWith('.png') ||
		pathname.endsWith('.jpg') ||
		pathname.endsWith('.svg')
		//pathname.startsWith('/api/')
	) return res

	const cookieStore = await cookies()
	const Authorization = cookieStore.get('token')
	
	if (publicRoutes.some((path) => pathname.startsWith(path))) {
		// Allow public routes to be accessed without authentication
		return res
	} else {
		if (protectedRoutes.some((path) => pathname.startsWith(path))) {
			if (!Authorization) {
				// not logged in.
				const url = new URL("/entrada", request.url)
				return NextResponse.redirect(url)
			}
		}
	}
 return res;
}