import { NextRequest, NextResponse } from "next/server"
import createMiddleware from 'next-intl/middleware'
import { routing } from './i18n/routing'

function isTokenExpired(token: string): boolean {
  try {
    const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString())
    return payload.exp * 1000 < Date.now()
  } catch {
    return true // Invalid token, consider expired
  }
}

const i18nMiddleware = createMiddleware(routing)

export function middleware(request: NextRequest) {
  // Read the token from cookies
  const token = request.cookies.get("iit_token")?.value
  const { pathname } = request.nextUrl

  // Extract locale from pathname (e.g., /en/dashboard -> en)
  const pathnameLocale = pathname.split('/')[1]
  const locale = ['en', 'fr'].includes(pathnameLocale) ? pathnameLocale : 'en'

  // Protect all /[locale]/dashboard routes
  if (pathname.match(/^\/[a-z]{2}\/dashboard/)) {
    if (!token || isTokenExpired(token)) {
      // Clear the expired token and redirect to sign-in
      const response = NextResponse.redirect(new URL(`/${locale}/sign-in`, request.url))
      response.cookies.delete("iit_token")
      return response
    }
  }

  // Redirect logged-in users away from /[locale]/sign-in or /[locale]/sign-up
  if (pathname.match(/^\/[a-z]{2}\/(sign-in|sign-up)$/) && token && !isTokenExpired(token)) {
    return NextResponse.redirect(new URL(`/${locale}/dashboard`, request.url))
  }

  // Handle i18n routing
  return i18nMiddleware(request)
}

export const config = {
  matcher: [
    // Match all pathnames except for
    // - /api (API routes)
    // - /_next (Next.js internals)
    // - /_vercel (Vercel internals)
    // - /.* (files in the root, e.g. favicon.ico)
    '/((?!api|_next|_vercel|.*\\.).*)'
  ]
}
