'use server';

import { GetMessageListResponse, MedipostAction } from '@/lib/types/medipost';
import axios from 'axios';

import { getLatestMessage } from './medipostMessageBase.service';

const BASE_URL = process.env.MEDIPOST_URL!;
const USER = process.env.MEDIPOST_USER!;
const PASSWORD = process.env.MEDIPOST_PASSWORD!;
const RECIPIENT = process.env.MEDIPOST_RECIPIENT!;

export async function getLatestPublicMessageListItem() {
  const { data } = await axios.get<GetMessageListResponse>(BASE_URL, {
    params: {
      Action: MedipostAction.GetPublicMessageList,
      User: USER,
      Password: PASSWORD,
      Sender: RECIPIENT,
      // LastChecked (date+time) can be used here to get only messages since the last check - add when cron is created
      // MessageType check only for messages of certain type
    },
  });

  if (data.code && data.code !== 0) {
    throw new Error('Failed to get public message list');
  }

  return await getLatestMessage({ messages: data?.messages });
}
