/**
 * How a document number is put together, laid out as the ERP's document-number
 * formatting: a row of parts, each switched on or off, in the office's order —
 * DN + "-" + WF + 26 + 10 + 01 → DN-WF261001. The Settings page draws its sample
 * from this and the server its numbers, so the two cannot disagree; for that it
 * imports nothing, and the admin app imports it as it is.
 */

export const NUMBER_PARTS = ['SYMBOL', 'TEXT1', 'TEXT2', 'COMPANY', 'YEAR', 'MONTH', 'DAY', 'SERIAL'] as const;
export type NumberPart = (typeof NUMBER_PARTS)[number];

export const RESET_PERIODS = ['NEVER', 'YEARLY', 'MONTHLY'] as const;
export type ResetPeriod = (typeof RESET_PERIODS)[number];

export interface NumberFormat {
  /** The ERP's "Symbol", e.g. DN. */
  prefix: string;
  /** The ERP's two "Special Strings", e.g. "-". */
  text1: string;
  text2: string;
  /** The parts shown, in order. */
  parts: readonly NumberPart[];
  /** The serial number's width. */
  padding: number;
}

/** What goes into one number: the landlord company's code, the document's
 *  date as "YYYYMMDD", and the count. */
export interface NumberValues {
  company: string;
  date: string;
  serial: number;
}

export function renderNumber(f: NumberFormat, v: NumberValues): string {
  const part: Record<NumberPart, () => string> = {
    SYMBOL: () => f.prefix,
    TEXT1: () => f.text1,
    TEXT2: () => f.text2,
    COMPANY: () => v.company,
    YEAR: () => v.date.slice(2, 4),
    MONTH: () => v.date.slice(4, 6),
    DAY: () => v.date.slice(6, 8),
    SERIAL: () => String(v.serial).padStart(f.padding, '0'),
  };
  return f.parts.map((p) => part[p]()).join('');
}

/** The period a count runs for, from the document's "YYYYMMDD": '' when it
 *  never restarts, the year when yearly, the month when monthly. The day is
 *  only ever shown — no count restarts daily, as in the ERP's "By Year and
 *  Month". */
export function periodOf(reset: string, date: string): string {
  if (reset === 'YEARLY') return date.slice(0, 4);
  if (reset === 'MONTHLY') return date.slice(0, 6);
  return '';
}

/** The parts a restart cannot do without — otherwise next year's 01 would be
 *  this year's 01 again. The ERP ticks them for you the same way. */
export function partsRequiredBy(reset: string): NumberPart[] {
  if (reset === 'YEARLY') return ['YEAR'];
  if (reset === 'MONTHLY') return ['YEAR', 'MONTH'];
  return [];
}

/** The stored comma list, read back. */
export function parseParts(stored: string): NumberPart[] {
  return stored.split(',').filter((p): p is NumberPart => (NUMBER_PARTS as readonly string[]).includes(p));
}
