/**
 * Hjälpfunktion för att wrappa Next.js Route Handlers med NextAuth auth().
 * Löser problemet med att auth() standalone inte fungerar i route handlers
 * med Next.js 15+/16 (async cookies-kompatibilitet i NextAuth beta).
 *
 * request.auth = session-objektet (inkl. accessToken)
 */
import { NextResponse } from 'next/server';
import { auth } from '../auth';

export type AuthedRequest = Request & { auth: { accessToken?: string; user?: any } | null };

/**
 * Returnerar Authorization-headern från en autentiserad request.
 * Kastar 401-svar om sessionen saknar accessToken.
 */
export function getBearer(session: AuthedRequest['auth']): string | null {
  if (!session?.accessToken) return null;
  return `Bearer ${session.accessToken}`;
}

/**
 * Wrapper: export const GET = withAuth(async (req, session, context) => { ... })
 */
export function withAuth(
  handler: (req: Request, session: NonNullable<AuthedRequest['auth']>, context: any) => Promise<Response>,
) {
  return auth(async function (request: any, context: any) {
    let session = request.auth;
    // eslint-disable-next-line no-console
    console.log('[withAuth] request.auth:', JSON.stringify(session));

    // Fallback: om wrapper-formen inte populerar request.auth, försök standalone
    if (!session?.accessToken) {
      // eslint-disable-next-line no-console
      console.log('[withAuth] Trying auth() standalone fallback...');
      session = await auth();
      // eslint-disable-next-line no-console
      console.log('[withAuth] standalone session:', JSON.stringify(session));
    }

    if (!session?.accessToken) {
      // eslint-disable-next-line no-console
      console.warn('[withAuth] No accessToken — returning 401');
      return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
    }
    return handler(request, session, context);
  });
}
