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

import oriyoClient from '@/app/api-utlities/utilities/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);

  try {
    const oriyoResponse = await oriyoClient.get('/client/login', {
      params: {
        type: validatedBody.type,
        phone: validatedBody.phoneNumber,
        uid: validatedBody.cardNumber,
      },
    });

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

    if (!parsedResponse.token) {
      return NextResponse.json({ error: 'Credentials error' }, { status: 401 });
    }

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

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

    return response;
  } catch (error) {
    console.error('login error:', error);
    return NextResponse.json({ error: 'Server error' }, { status: 500 });
  }
};

export const POST = validationErrorHandler(routeHandler);
