import { NextResponse } from 'next/server';

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

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

export async function POST(request: Request) {
  // const isDev = process.env.NODE_ENV === 'development';
  // if (!isDev) {
  //   return NextResponse.json({ error: 'This endpoint is only available in development mode' }, { status: 403 });
  // }

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

  const medusaOrder = await retrieveOrder(medusaOrderId);
  const analysisOrder = await getAnalysisOrder({ medusaOrderId });

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

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

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

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