import { format } from 'date-fns';
import Isikukood from 'isikukood';

/**
 * Check if the code is running in a browser environment.
 */
export function isBrowser() {
  return typeof window !== 'undefined';
}

/**
 * @name formatCurrency
 * @description Format the currency based on the currency code
 */
export function formatCurrency(params: {
  currencyCode: string;
  locale: string;
  value: string | number;
}) {
  const [lang, region] = (params.locale ?? 'et-ET').split('-');

  return new Intl.NumberFormat(region ?? lang, {
    style: 'currency',
    currency: params.currencyCode,
  }).format(Number(params.value));
}

export function formatDateAndTime(date?: string) {
  if (!date) return '-';

  return format(date, 'dd.MM.yyyy HH:mm');
}

export function formatDate(date?: string) {
  if (!date) return '-';

  return format(date, 'dd.MM.yyyy');
}

export function getFullName(
  firstName?: string | null,
  lastName?: string | null,
) {
  return [firstName ?? '', lastName ?? ''].join(' ');
}

export const getPersonParameters = (personalCode: string) => {
  try {
    const person = new Isikukood(personalCode);
    return {
      gender: person.getGender(),
      dob: person.getBirthday(),
      age: person.getAge(),
    };
  } catch (error) {
    console.error(error);
    return null;
  }
};

export function toArray<T>(input?: T | T[] | null): T[] {
  if (!input) return [];
  return Array.isArray(input) ? input : [input];
}
