import { NextResponse } from 'next/server';
import { getSession, SessionPayload } from '@server/auth';
import { AuthError } from '@server/errors';
import { RouteContext, RouteHandler } from './withErrorHandler';

export type AuthedRequest = Request & { session: SessionPayload };

export type AuthedHandler = (
  req: AuthedRequest,
  context: RouteContext
) => Promise<NextResponse | Response>;

export function withAuth(handler: AuthedHandler | RouteHandler): RouteHandler {
  return async (req, context) => {
    const session = await getSession();

    if (!session) {
      const err = new AuthError();
      return NextResponse.json(err.toJSON(), { status: err.statusCode });
    }

    Object.defineProperty(req, 'session', {
      value: session,
      writable: false,
      enumerable: true,
      configurable: true,
    });

    return handler(req as AuthedRequest, context);
  };
}
