import { RequestCookie } from 'next/dist/compiled/@edge-runtime/cookies';
import { NextRequest } from 'next/server';

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

import { authorizationMiddleware } from '../../middlewares/auth.middleware';
import { validationErrorHandler } from '../../middlewares/error-handler.middleware';

const routeHandler = async (req: NextRequest, requestCookie: RequestCookie) => {
  const { card_id, token } = JSON.parse(requestCookie.value);

  const oriyoResponse = await oriyoClient.get('/bonuscardinfo', {
    params: {
      card_id,
      token,
    },
  });

  if (oriyoResponse.status === 401) {
    throw new AuthorizationError();
  }

  return new Response(JSON.stringify(oriyoResponse.data), {
    headers: { 'Content-Type': 'application/json' },
  });
};

export const GET = validationErrorHandler(
  authorizationMiddleware(routeHandler, 'bonus__token'),
);
