import { GeneralSettings } from '../api/settings'

/**
 * Formats a date string or object based on user settings
 */
export const formatDate = (date: string | Date | number, settings?: GeneralSettings): string => {
    if (!date) return 'N/A'

    const d = typeof date === 'string' && !date.includes('Z') && !date.includes('+')
        ? new Date(date + 'Z') // Ensure UTC if no timezone info
        : new Date(date)

    if (isNaN(d.getTime())) return 'Invalid Date'

    const timezone = settings?.timezone || 'local'

    const options: Intl.DateTimeFormatOptions = {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
    }

    if (timezone !== 'local') {
        options.timeZone = timezone
    }

    return d.toLocaleString(undefined, options)
}

/**
 * Formats only the time part
 */
export const formatTime = (date: string | Date | number, settings?: GeneralSettings): string => {
    if (!date) return 'N/A'

    const d = typeof date === 'string' && !date.includes('Z') && !date.includes('+')
        ? new Date(date + 'Z')
        : new Date(date)

    if (isNaN(d.getTime())) return 'N/A'

    const timezone = settings?.timezone || 'local'

    const options: Intl.DateTimeFormatOptions = {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
    }

    if (timezone !== 'local') {
        options.timeZone = timezone
    }

    return d.toLocaleTimeString(undefined, options)
}
