//! GlobalDateTime functions are server only
//! Servers require a specific reference to timeZone since most of our servers are in UTC

import { formatISO9075 } from 'date-fns';
import { formatInTimeZone } from 'date-fns-tz';
import config from 'config';
import {
  ISO9075_DATE_FORMAT,
  ISO9075_DATETIME_FORMAT,
} from '@tamanu/utils/dateTime';
import { getPrimaryTimeZone } from './timeZoneCheck';

const primaryTimeZone = getPrimaryTimeZone(config);

export function toPrimaryDateTimeString(date) {
  if (date === null || date === undefined) {
    return null;
  }

  return formatInTimeZone(date, primaryTimeZone, ISO9075_DATETIME_FORMAT);
}

export function toPrimaryDateString(date) {
  if (date === null || date === undefined) {
    return null;
  }

  return formatInTimeZone(date, primaryTimeZone, ISO9075_DATE_FORMAT);
}

export function getCurrentPrimaryTimeZoneDateTimeString() {
  if (primaryTimeZone) {
    return formatInTimeZone(new Date(), primaryTimeZone, ISO9075_DATETIME_FORMAT);
  }
  return formatISO9075(new Date());
}

export function getCurrentPrimaryTimeZoneDateString() {
  if (primaryTimeZone) {
    return formatInTimeZone(new Date(), primaryTimeZone, ISO9075_DATE_FORMAT);
  }
  return formatISO9075(new Date(), { representation: 'date' });
}
