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

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

import { loginFormSchema } from '@/entities/auth/model/validation/login-form.schema';

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

const routeHandler = async (req: NextRequest) => {
  const body = await req.json();

  const validatedBody = loginFormSchema
    .merge(z.object({ type: z.enum(['bonus', 'corporate']) }))
    .parse(body);

  const oriyoResponse = await (() => {
    switch (validatedBody.type) {
      case 'corporate':
        return oriyoClient.get('/corporatecard', {
          params: {
            phone: validatedBody.phoneNumber,
            uid: validatedBody.cardNumber,
          },
        });

      default:
        return oriyoClient.get('/bonuscard', {
          params: {
            phone: validatedBody.phoneNumber,
            uid: validatedBody.cardNumber,
          },
        });
    }
  })();

  if (oriyoResponse.data.error)
    return NextResponse.json({ error: 'Credentials error' }, { status: 401 });

  const response = NextResponse.json({ success: true });

  response.cookies.set(
    `${validatedBody.type}__token`,
    JSON.stringify(oriyoResponse.data),
    {
      path: '/',
      maxAge: 2 * 60 * 60,
    },
  );

  return response;
};

export const POST = validationErrorHandler(routeHandler);
