import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
import { COUNT_PER_PAGE } from "./constants";

// Tailwind CSS class merge
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

// CommonUtils.checkNull 대응
export function checkNull(value: unknown, defaultValue = ""): string {
  if (value === null || value === undefined || value === "null" || value === "undefined") {
    return defaultValue;
  }
  return String(value);
}

// CommonUtils.isEmpty 대응
export function isEmpty(value: unknown): boolean {
  if (value === null || value === undefined) return true;
  if (typeof value === "string") return value.trim() === "";
  return false;
}

export function isNotEmpty(value: unknown): boolean {
  return !isEmpty(value);
}

// CommonUtils.setPagingInfo 대응
export function setPagingInfo(
  totalCount: number,
  currentPage: number,
  countPerPage = COUNT_PER_PAGE
) {
  const maxPage = Math.max(1, Math.ceil(totalCount / countPerPage));
  const safePage = Math.min(Math.max(1, currentPage), maxPage);
  const pageStart = (safePage - 1) * countPerPage + 1;
  const pageEnd = safePage * countPerPage;

  return {
    totalCount,
    countPerPage,
    currentPage: safePage,
    maxPage,
    pageStart,
    pageEnd,
  };
}

// numberWithCommas (common.js 대응)
export function numberWithCommas(x: number | string): string {
  if (x === null || x === undefined) return "";
  return String(x).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

// 날짜 포맷 (fnc_getDate 대응)
export function getDate(delimiter = "-"): string {
  const now = new Date();
  const y = now.getFullYear();
  const m = String(now.getMonth() + 1).padStart(2, "0");
  const d = String(now.getDate()).padStart(2, "0");
  return `${y}${delimiter}${m}${delimiter}${d}`;
}

// Object ID 생성 (common/createObjectId.do 대응)
export function createObjectId(): string {
  return String(Date.now()) + String(Math.floor(Math.random() * 10000));
}

// CommonUtils.getNextRevision 대응 — A→B, Z→AA, AZ→BA, ZZ→ZZ(cap)
export function getNextRevision(prev: string): string {
  const p = String(prev || "").toUpperCase();
  if (p.length >= 3 || p === "ZZ") return "ZZ";
  if (p.length === 2) {
    const c0 = p.charCodeAt(0);
    const c1 = p.charCodeAt(1);
    if (c1 < 90) return p[0] + String.fromCharCode(c1 + 1);
    if (c1 === 90) return String.fromCharCode(c0 + 1) + "A";
  }
  if (p.length === 1) {
    const c = p.charCodeAt(0);
    if (c < 90) return String.fromCharCode(c + 1);
    if (c === 90) return "AA";
  }
  return "";
}

// Map 키 대문자 변환 (CommonUtils.toUpperCaseMapKey 대응)
export function toUpperCaseMapKey<T extends Record<string, unknown>>(
  rows: T[]
): Record<string, unknown>[] {
  return rows.map((row) => {
    const result: Record<string, unknown> = {};
    for (const [key, value] of Object.entries(row)) {
      result[key.toUpperCase()] = value;
    }
    return result;
  });
}
