'use server';

import { updateLineItem } from '@lib/data/cart';
import { StoreProductVariant } from '@medusajs/types';

import logRequestResult from '~/lib/services/audit.service';
import { handleAddToCart } from '~/lib/services/medusaCart.service';
import {
  cancelReservation,
  createInitialReservation,
} from '~/lib/services/reservation.service';
import { RequestStatus } from '~/lib/types/audit';
import { ConnectedOnlineMethodName } from '~/lib/types/connected-online';
import { ExternalApi } from '~/lib/types/external';

export async function createInitialReservationAction(
  selectedVariant: Pick<StoreProductVariant, 'id'>,
  countryCode: string,
  serviceId: number,
  clinicId: number,
  appointmentUserId: number,
  syncUserId: number,
  startTime: Date,
  locationId: number | null,
  comments?: string,
) {
  const { addedItem } = await handleAddToCart({
    selectedVariant,
    countryCode,
  });

  if (addedItem) {
    const reservation = await createInitialReservation({
      serviceId,
      clinicId,
      appointmentUserId,
      syncUserID: syncUserId,
      startTime,
      medusaLineItemId: addedItem.id,
      locationId,
      comments,
    });

    await updateLineItem({
      lineId: addedItem.id,
      quantity: addedItem.quantity,
      metadata: { connectedOnlineReservationId: reservation.id },
    });
  }
}

export async function cancelTtoBooking(
  bookingCode: string,
  clinicId: number,
  medusaLineItemId: string,
) {
  try {
    await fetch(
      `${process.env.CONNECTED_ONLINE_URL}/${ConnectedOnlineMethodName.ConfirmedCancel}`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
        },
        body: JSON.stringify({
          param: `{'Value':'${bookingCode}|${clinicId}|et'}`,
        }),
      },
    );

    await cancelReservation(medusaLineItemId);

    await logRequestResult(
      ExternalApi.ConnectedOnline,
      ConnectedOnlineMethodName.ConfirmedCancel,
      RequestStatus.Success,
      medusaLineItemId,
    );
  } catch (error) {
    await logRequestResult(
      ExternalApi.ConnectedOnline,
      ConnectedOnlineMethodName.ConfirmedCancel,
      RequestStatus.Fail,
      JSON.stringify(error),
    );
    if (error instanceof Error) {
      console.error('Error cancelling booking: ' + error.message);
    }
    console.error('Error cancelling booking: ', error);
  }
}
