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

import oriyoClient from '@/app/api-utlities/utilities/oriyo.client';

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) => {
  const bonusTokenData = req.cookies.get('bonus__token');

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

  const params = Array.from(req.nextUrl.searchParams.entries()).reduce(
    (pr, cr) => {
      pr[cr[0]] = cr[1];

      return pr;
    },
    {} as Record<string, string>,
  );

  const validatedRequest = validatedSchema.parse(params);

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

  const oriyoResponse = await oriyoClient.get('/client/transactions', {
    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,
    },
  });

  const parsedResponse = JSON.parse(oriyoResponse.data);

  if (parsedResponse.error) {
    return NextResponse.json({ message: 'Fetch error' }, { status: 400 });
  }

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

export const GET = validationErrorHandler(routeHandler);
