import _dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import utc from 'dayjs/plugin/utc'

_dayjs.extend(customParseFormat)
_dayjs.extend(utc)

const ISO_PREFIX = /^\d{4}-\d{2}-\d{2}T/
const HAS_Z_TOKEN = /(?<!\[)ZZ?/

const dayjs = (date, format, strict) => {
  if (format) {
    const result = _dayjs(date, format, strict)
    if (!result.isValid() && typeof date === 'string' && ISO_PREFIX.test(date)) {
      const formats = Array.isArray(format) ? format : [format]
      if (formats.some(f => HAS_Z_TOKEN.test(f))) {
        return _dayjs(date)
      }
    }
    return result
  }
  return _dayjs(date)
}

dayjs.utc = _dayjs.utc
dayjs.extend = _dayjs.extend
dayjs.locale = _dayjs.locale
dayjs.isDayjs = _dayjs.isDayjs

export default dayjs
