import { Injectable } from '@angular/core';

import { DATE_TIME_FORMATS } from '../constants/date-time-formats';
import { DateTimeFormat } from '../models/date-time-format';

export interface DateTimeFormattingOptions {
  readonly format?: DateTimeFormat;
  readonly locale?: string;
  readonly timeZone?: string;
  readonly fallback?: string;
}

@Injectable({
  providedIn: 'root'
})
export class DateTimeFormatterService {
  format(
    value: string | number | Date | null | undefined,
    options: DateTimeFormattingOptions = {}
  ): string {
    const fallback = options.fallback ?? '—';

    if (value === null || value === undefined || (typeof value === 'string' && !value.trim())) {
      return fallback;
    }

    const date = value instanceof Date
      ? new Date(value.getTime())
      : new Date(value);

    if (Number.isNaN(date.getTime())) {
      return fallback;
    }

    const format = options.format ?? DateTimeFormat.DateTime;
    const locale = options.locale?.trim() || 'en-GB';
    const timeZone = options.timeZone?.trim();

    try {
      return new Intl.DateTimeFormat(locale, {
        ...DATE_TIME_FORMATS[format],
        ...(timeZone ? { timeZone } : {})
      }).format(date);
    } catch {
      return fallback;
    }
  }
}
