/** The billing month stuck on a charge ("Rent · 2026-10") is the note's period,
 *  not the line's coverage. A quarterly rate billed in October covers October
 *  to December, so that month would disagree with the Period columns. Those
 *  columns are the only dates Particulars prints. */
export function printedParticulars(description: string): string {
  return description.replace(/\s*·\s*\d{4}-\d{2}(?=\s|$)/g, '').replace(/\s{2,}/g, ' ').trim();
}

/** Letterhead contact line shipped before the company email was printed.
 *  Matched exactly so a template the office has rewritten is left alone. */
const LEGACY_CONTACT =
  '<span>{{#if org.tel}}Tel : {{org.tel}}{{/if}}{{#if org.fax}} &nbsp; Fax : {{org.fax}}{{/if}}</span>';
const CONTACT_WITH_EMAIL =
  '<span class="contact">{{#if org.tel}}Tel : {{org.tel}}{{/if}}{{#if org.fax}} &nbsp; Fax : {{org.fax}}{{/if}}{{#if org.email}}<br>Email : {{org.email}}{{/if}}</span>';

/** The tenant lines shipped before the tenant's address and email were printed,
 *  each followed by what now comes after it. Matched exactly, as above. */
const TENANT_NAME = '<div>{{tenant.name}}</div>';
const TENANT_ADDRESS = '{{#if tenant.address}}<div style="white-space:pre-line">{{tenant.address}}</div>{{/if}}';
const TENANT_TEL = '{{#if tenant.phone}}<tr><td>Tel No. :</td><td>{{tenant.phone}}</td></tr>{{/if}}';
const TENANT_EMAIL = '{{#if tenant.email}}<tr><td>Email :</td><td>{{tenant.email}}</td></tr>{{/if}}';

/** Puts the tenant's address under its name and its email under its phone on a
 *  debit-note template that has neither. Each is left alone once printed, or
 *  where the office has rewritten the line it would follow. */
export function withTenantContact(body: string): string {
  let next = body;
  if (!next.includes('tenant.address') && next.includes(TENANT_NAME)) next = next.replace(TENANT_NAME, TENANT_NAME + TENANT_ADDRESS);
  if (!next.includes('tenant.email') && next.includes(TENANT_TEL)) next = next.replace(TENANT_TEL, TENANT_TEL + TENANT_EMAIL);
  return next;
}

/** Puts the company email on a debit-note template that still has the old
 *  Tel / Fax line. A template that already prints {{org.email}} is unchanged. */
export function withCompanyEmail(body: string): string {
  if (body.includes('org.email') || !body.includes(LEGACY_CONTACT)) return body;
  let next = body.replace(LEGACY_CONTACT, CONTACT_WITH_EMAIL);
  if (!next.includes('.subhead .contact')) {
    next = next.replace(
      /\.dn \.subhead \{ display: flex; justify-content: space-between; font-size: 7\.5pt; font-style: italic;\s*border-bottom: 1px solid #000; padding-bottom: 2mm; \}/,
      `.dn .subhead { display: flex; justify-content: space-between; gap: 6mm; align-items: flex-start; font-size: 7.5pt; font-style: italic;
                 border-bottom: 1px solid #000; padding-bottom: 2mm; }
  .dn .subhead .contact { text-align: right; line-height: 1.45; }`,
    );
  }
  return next;
}
