/**
 * dayjs با تقویم جلالی.
 * فرمت‌های API/ICS با خط تیره یا YYYYMMDD همیشه میلادی برمی‌گردند.
 */
import dayjs from "dayjs";
import jalaliday from "jalaliday";
import "dayjs/locale/fa";
import customParseFormat from "dayjs/plugin/customParseFormat";
import utc from "dayjs/plugin/utc";
import relativeTime from "dayjs/plugin/relativeTime";

dayjs.extend(jalaliday);
dayjs.extend(customParseFormat);
dayjs.extend(utc);
dayjs.extend(relativeTime);
dayjs.locale("fa");
dayjs.calendar("jalali");

const originalFormat = dayjs.prototype.format;

if (!(dayjs.prototype as unknown as { __jalaliApiPatched?: boolean }).__jalaliApiPatched) {
  dayjs.prototype.format = function format(template?: string) {
    if (
      typeof template === "string" &&
      typeof this.calendar === "function" &&
      (/Y{2,4}-M{1,2}-D{1,2}/.test(template) || /Y{4}M{2}D{2}/.test(template))
    ) {
      return originalFormat.call(this.calendar("gregory"), template);
    }
    return originalFormat.call(this, template);
  };
  (dayjs.prototype as unknown as { __jalaliApiPatched?: boolean }).__jalaliApiPatched = true;
}

export default dayjs;
