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

import {
  parseSessionCookie,
  serializeSessionData,
  SESSION_COOKIE_NAME,
} from './lib/session';

export function middleware(request: NextRequest) {
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-pathname', request.nextUrl.pathname);

  const cookieValue = request.cookies.get(SESSION_COOKIE_NAME)?.value;
  const sessionData = parseSessionCookie(cookieValue);

  if (sessionData.userId) {
    return NextResponse.next({ request: { headers: requestHeaders } });
  }

  sessionData.userId = crypto.randomUUID();
  sessionData.updatedAt = new Date().toISOString();

  const response = NextResponse.next({ request: { headers: requestHeaders } });
  response.cookies.set(SESSION_COOKIE_NAME, serializeSessionData(sessionData), {
    path: '/',
    httpOnly: true,
    sameSite: 'lax',
    maxAge: 60 * 60 * 24,
  });

  return response;
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
