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

import { retrieveOrder } from '@lib/data/orders';

import { getMedipostDispatchTries } from '~/lib/services/audit.service';
import { sendOrderToMedipost } from '~/lib/services/medipost/medipostPrivateMessage.service';
import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service';

import loadEnv from '../handler/load-env';
import validateApiKey from '../handler/validate-api-key';

export const POST = async (request: NextRequest) => {
  loadEnv();

  const { medusaOrderId } = await request.json();

  try {
    validateApiKey(request);
  } catch (e) {
    return NextResponse.json({}, { status: 401, statusText: 'Unauthorized' });
  }

  const tries = await getMedipostDispatchTries(medusaOrderId);
  if (tries >= 3) {
    return NextResponse.json(
      {
        message: 'Order has been retried too many times',
      },
      { status: 400 },
    );
  }

  try {
    const medusaOrder = await retrieveOrder(medusaOrderId);
    const orderedAnalysisElements = await getOrderedAnalysisIds({
      medusaOrder,
    });
    await sendOrderToMedipost({ medusaOrderId, orderedAnalysisElements });
    console.info('Successfully sent order to medipost');
    return NextResponse.json(
      {
        message: 'Successfully sent order to medipost',
      },
      { status: 200 },
    );
  } catch (e) {
    console.error('Error sending order to medipost', e);
    return NextResponse.json(
      {
        message: 'Failed to send order to medipost',
      },
      { status: 500 },
    );
  }
};
