import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';

const PORTAL_HOSTS = new Set(['portal.sankofa.nexus']);

export async function middleware(request: NextRequest) {
  const host = request.headers.get('host')?.split(':')[0] ?? '';
  if (!PORTAL_HOSTS.has(host)) {
    return NextResponse.next();
  }

  const token = await getToken({
    req: request,
    secret: process.env.NEXTAUTH_SECRET,
  });
  if (token) {
    return NextResponse.next();
  }

  const signIn = request.nextUrl.clone();
  signIn.pathname = '/api/auth/signin';
  signIn.searchParams.set('callbackUrl', '/dashboard');
  return NextResponse.redirect(signIn);
}

export const config = {
  matcher: ['/'],
};
