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

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

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

const validatedSchema = z.object({
  start_date: z.string().optional(),
  end_date: z.string().optional(),
  limit: z.coerce.number(),
  page: z.coerce.number(),
});

const routeHandler = async (req: NextRequest, requestCookie: RequestCookie) => {
  const validatedRequest = validatedSchema.parse(getParams(req));

  const { card_id, token } = JSON.parse(requestCookie.value);

  const oriyoResponse = await oriyoClient.get('/bonuscardts', {
    params: {
      card_id,
      token,
      limit: validatedRequest.limit,
      page: validatedRequest.page,
      type: 'bonus',
      sort: 'id',
      direction: 'desc',
      start_date: validatedRequest.start_date,
      end_date: validatedRequest.end_date,
    },
  });

  if (oriyoResponse.status === 404)
    return new Response(
      JSON.stringify({
        transactions: [],
        card_id,
        current_page: validatedRequest.page,
        limit: validatedRequest.limit,
        total_records: 0,
        total_pages: 0,
      }),
      {
        headers: { 'Content-Type': 'application/json' },
      },
    );

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

  if (oriyoResponse.data.error) throw oriyoResponse.data;

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

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