const ORDER_NO_RE = /^ORD-(\d+)$/;
const EMPLOYEE_CODE_RE = /^KCE-(\d+)$/;

export function generateOrderNo(lastOrderNo?: string): string {
  if (!lastOrderNo) return 'ORD-3001';
  const match = ORDER_NO_RE.exec(lastOrderNo);
  const seq = match ? Number(match[1]) : 3000;
  return `ORD-${seq + 1}`;
}

export function generateEmployeeCode(lastCode?: string): string {
  if (!lastCode) return 'KCE-1';
  const match = EMPLOYEE_CODE_RE.exec(lastCode);
  const seq = match ? Number(match[1]) : 0;
  return `KCE-${seq + 1}`;
}

function pad(n: number): string {
  return String(n).padStart(2, '0');
}

// Local wall-clock date+time as 'YYYY-MM-DD HH:MM:SS', for DATETIME columns
// that need the actual moment something happened, not just the day.
// Deliberately NOT `new Date().toISOString()`, which converts to UTC first —
// for a timezone ahead of UTC (e.g. IST, UTC+5:30) that silently shifts
// both the date and time back, e.g. mislabeling same-day events as having
// happened before they actually did whenever compared/sorted against a
// correctly-local timestamp.
export function now(): string {
  const d = new Date();
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

export function todayDate(): string {
  const d = new Date();
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
