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

import { AuthorizationError } from '@/app/api-utlities/errors/authorization.error';

export const authorizationMiddleware =
  (handler: Function, authorizationTokenKey: string) =>
  async (req: NextRequest, ...args: any[]) => {
    const requestedToken = req.cookies.get(authorizationTokenKey);

    if (!requestedToken) {
      return NextResponse.json(
        { error: 'User does not have access' },
        { status: 401 },
      );
    }

    try {
      return await handler(req, requestedToken, ...args);
    } catch (error) {
      if (error instanceof AuthorizationError) {
        const response = NextResponse.json(
          { message: 'Authorization session was timed out' },
          { status: 401 },
        );

        response.cookies.delete(authorizationTokenKey);

        return response;
      }

      throw error;
    }
  };
