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

import { getURL } from './lib/utils';

/**
 * Permet de créer un middleware Next.js qui sera exécuté avant chaque requête.
 *
 * @param req - La requête Next.js
 */
export async function middleware(req: NextRequest) {
  const res = NextResponse.next();

  const token = req.cookies.get('token')?.value || '';

  // TODO: Refactor middleware, waiting for api

  // if (req.nextUrl.pathname === '/') {
  //   return NextResponse.redirect(getURL('/sign-in'), {
  //     status: 301
  //   });
  // }

  const isAuth = await validateToken(token);

  if (!isAuth) {
    res.cookies.set('token', '', {
      path: '/',
      expires: new Date(0)
    });

    if (req.nextUrl.pathname.includes('dashboard') || req.nextUrl.pathname.includes('event')) {
      return NextResponse.redirect(getURL('/sign-in'));
    }

    return res;
  }

  if (isAuth && req.nextUrl.pathname.includes('logout')) {
    res.cookies.set('token', '', {
      path: '/',
      expires: new Date(0)
    });
  }

  if (isAuth && req.nextUrl.pathname.includes('sign')) {
    return NextResponse.redirect(getURL('/dashboard'));
  }

  return res;
}

export const config = {
  matcher: [
    // On exclut les routes de l'API, les fichiers statiques, les images, les assets, le favicon et le service worker.
    '/((?!api|_next/static|_next/image|favicon.ico|assets|sw.js).*)'
  ]
};

async function validateToken(token: string | undefined) {
  if (!token) {
    return false;
  }

  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/player/`, {
      headers: {
        Authorization: `Bearer ${token}`
      },
      cache: 'force-cache',
      next: {
        revalidate: 30
      }
    });

    return response.ok;
  } catch (error) {
    console.error('Error validating token:', error);
    return false;
  }
}
