import { CronExpressionParser } from 'cron-parser';

export function parseCron(expr: string): { valid: boolean; error?: string } {
  try {
    CronExpressionParser.parse(expr);
    return { valid: true };
  } catch (err) {
    return { valid: false, error: String(err) };
  }
}

export function getNextRun(expr: string): Date | null {
  try {
    const interval = CronExpressionParser.parse(expr);
    return interval.next().toDate();
  } catch {
    return null;
  }
}

export function cronToHuman(expr: string): string {
  const parts = expr.trim().split(/\s+/);
  if (parts.length < 5) return expr;

  const [min, hour, dom, mon, dow] = parts;

  if (min === '0' && hour === '*' && dom === '*' && mon === '*' && dow === '*') {
    return 'Every hour';
  }
  if (dom === '*' && mon === '*' && dow === '*') {
    if (hour === '*') return `Every hour at :${min?.padStart(2, '0')}`;
    return `Daily at ${hour}:${min?.padStart(2, '0')}`;
  }
  if (mon === '*' && dow !== '*') {
    const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    const dayName = days[Number(dow)] || dow;
    return `Every ${dayName} at ${hour}:${min?.padStart(2, '0')}`;
  }

  return expr;
}

export function shouldRunNow(expr: string, lastRun?: number): boolean {
  try {
    const interval = CronExpressionParser.parse(expr);
    const prev = interval.prev().toDate();
    const prevMs = prev.getTime();

    if (!lastRun) return true;
    return prevMs > lastRun;
  } catch {
    return false;
  }
}
