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

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

import { getAccountAdmin } from '~/lib/services/account.service';
import {
  composeOrderTestResponseXML,
  sendPrivateMessageTestResponse,
} from '~/lib/services/medipost/medipostTest.service';
import { getOrderedAnalysisIds } from '~/lib/services/medusaOrder.service';
import { getAnalysisOrdersAdmin } from '~/lib/services/order.service';

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

export async function POST(request: NextRequest) {
  loadEnv();

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

  const analysisOrders = await getAnalysisOrdersAdmin({
    orderStatus: 'PROCESSING',
  });

  console.error(
    `Sending test responses for ${analysisOrders.length} analysis orders`,
  );
  for (const medreportOrder of analysisOrders) {
    const medusaOrderId = medreportOrder.medusa_order_id;
    const medusaOrder = await retrieveOrder(medusaOrderId);

    const account = await getAccountAdmin({
      primaryOwnerUserId: medreportOrder.user_id,
    });
    const orderedAnalysisElementsIds = await getOrderedAnalysisIds({
      medusaOrder,
    });

    console.info(
      `Sending test response for order=${medusaOrderId} with ${orderedAnalysisElementsIds.length} ordered analysis elements`,
    );
    const idsToSend = orderedAnalysisElementsIds;
    const messageXml = await composeOrderTestResponseXML({
      person: {
        idCode: account.personal_code!,
        firstName: account.name ?? '',
        lastName: account.last_name ?? '',
        phone: account.phone ?? '',
      },
      orderedAnalysisElementsIds: idsToSend
        .map(({ analysisElementId }) => analysisElementId)
        .filter(Boolean) as number[],
      orderedAnalysesIds: idsToSend
        .map(({ analysisId }) => analysisId)
        .filter(Boolean) as number[],
      orderId: medreportOrder.id,
      orderCreatedAt: new Date(medreportOrder.created_at),
    });

    try {
      await sendPrivateMessageTestResponse({ messageXml });
    } catch (error) {
      console.error('Error sending private message test response: ', error);
    }
  }

  return NextResponse.json({ success: true });
}
