import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';

/** Tailwind className 合并工具 */
export function cn(...inputs: ClassValue[]): string {
  return twMerge(clsx(inputs));
}

/** 日期格式化 */
export function formatDate(
  date: Date | string | number,
  format = 'YYYY-MM-DD',
): string {
  const d = new Date(date);
  const pad = (n: number): string => String(n).padStart(2, '0');
  const map: Record<string, string> = {
    YYYY: String(d.getFullYear()),
    MM: pad(d.getMonth() + 1),
    DD: pad(d.getDate()),
    HH: pad(d.getHours()),
    mm: pad(d.getMinutes()),
    ss: pad(d.getSeconds()),
  };
  return format.replace(/YYYY|MM|DD|HH|mm|ss/g, (m) => map[m]);
}

/** 拼接上传图片绝对 URL */
export function resolveUploadUrl(p?: string | null): string {
  if (!p) return '';
  if (/^https?:\/\//i.test(p)) return p;
  const base = process.env.NEXT_PUBLIC_UPLOAD_URL ?? 'http://localhost:3001';
  return `${base.replace(/\/$/, '')}${p.startsWith('/') ? '' : '/'}${p}`;
}
