/**
 *
 * @description This page represent the middleware which contain the function
 * that stay between the request and the source , it filter them and do what must be do
 * for example it protect the must to be user api routes
 * * source : https://nextjs.org/docs/app/building-your-application/routing/middleware
 */

import createIntlMiddleware from 'next-intl/middleware';
import { NextRequest } from 'next/server';
import { NextResponse } from 'next/server'
import validateAuthToken from '@/middleware/validateAuthToken'

export default async function middleware(request: NextRequest) {

  // log the request general informations
  let ip = request.ip ?? request.headers.get('X-Forwarded-For')?.split(':')[3]
  console.log("request to : " ,request.nextUrl.pathname , 'from ip :' , ip)

  // handle pages
  if(!request.nextUrl.pathname.startsWith('/api'))
  {
    // handle next-intl Internationalization
    const defaultLocale = request.headers.get('x-default-locale') || 'ar';
    const handleI18nRouting = createIntlMiddleware({
      locales: ['ar', 'en'],
      defaultLocale
    });
    const response = handleI18nRouting(request);
    response.headers.set('x-default-locale', defaultLocale);
    
    return response;
  }

  // handle api routes
  // must be user routes

  // protect /api/user routes
  if(request.nextUrl.pathname.startsWith('/api/user'))
  {
    let authToken : {name:string , value : string} | undefined = request.cookies.get('authToken')
    let authValidation : boolean | undefined = await validateAuthToken(authToken?.value)

    if(!authValidation)
    { // you are not auth you cant access this route
      return new NextResponse(
        JSON.stringify({
          success: false,
          message: "notAllowed",
          // @ts-ignore
        } , {status : 405 , headers: { 'content-type': 'application/json'}})
      )
    }
    // you can access the api route
    return NextResponse.next()
  }
}

// represent the routes that this middleware supposed to handle them
export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)']
};