// ═══════════════════════════════════════════════════════════════════════════
// Company documents (Job Registrar packs) — 2026-11-10
// Which Stage 1 / Stage 2 forms exist, which are ticked by default for a given
// set of standards, and which typed fields each form prints.
// Template files: src/certificates/templates/{stage1,stage2}/ via src/pdf/template-registry.ts
// Template ids: scheme_dbs.templates (also used for the audit-plan time slots in template_contents).
// ═══════════════════════════════════════════════════════════════════════════

export type PackStage = 'stage1' | 'stage2';

/** Typed fields a form prints (used to tell the user which inputs matter, and to require approval date). */
export type PackField =
  | 'approvedDate'
  | 'prepareDate'
  | 'docReview'
  | 'numEmployees'
  | 'naceEacCodes'
  | 'md'
  | 'mdRisk'
  | 'technicalExpert';

/** Q = ISO 9001 (QMS), E = ISO 14001 (EMS), O = ISO 45001 (OH&S). */
export type StdKey = 'Q' | 'E' | 'O';

export interface PackForm {
  key: string; // unique within the stage
  stage: PackStage;
  registryKey: string; // key in template-registry.ts
  templateId: number | null; // scheme_dbs.templates.id (time slots for audit plans)
  title: string;
  formNo?: string;
  /** Plan variant: ticked only when the audit's standards are exactly this combination. */
  variantFor?: string; // e.g. 'Q', 'QE', 'QEO', '' (blank / no Q-E-O standard)
  /** Client data sheet for one standard: ticked when that standard is on the audit. */
  forStd?: StdKey;
  /** Ticked by default (when not a variant / per-standard form). */
  defaultOn?: boolean;
  fields: PackField[];
}

const PLAN_FIELDS: PackField[] = ['naceEacCodes', 'technicalExpert'];
const SHEET_FIELDS: PackField[] = ['approvedDate', 'prepareDate', 'numEmployees', 'naceEacCodes', 'md', 'mdRisk'];

export const PACK_FORMS: PackForm[] = [
  // ───────────── Stage 1 ─────────────
  { key: 'initial-inquiry', stage: 'stage1', registryKey: 'initial-inquiry', templateId: 7, title: 'Initial Inquiry', formNo: '02-1', defaultOn: true, fields: ['numEmployees'] },
  { key: 'client-sheet-qms', stage: 'stage1', registryKey: 'form-02-4a-client-sheet', templateId: 42, title: 'Client Data Sheet – QMS', formNo: '02-4a', forStd: 'Q', fields: SHEET_FIELDS },
  { key: 'client-sheet-ems', stage: 'stage1', registryKey: 'form-02-4b-client-sheet', templateId: 43, title: 'Client Data Sheet – Environment', formNo: '02-4b', forStd: 'E', fields: SHEET_FIELDS },
  { key: 'client-sheet-ohs', stage: 'stage1', registryKey: 'form-02-4c-client-sheet', templateId: 62, title: 'Client Data Sheet – Health & Safety', formNo: '02-4c', forStd: 'O', fields: SHEET_FIELDS },
  { key: 'audit-time-plan', stage: 'stage1', registryKey: 'audit-time-plan', templateId: 4, title: 'Audit Time Justification Plan', formNo: '04-1', defaultOn: true, fields: ['numEmployees', 'naceEacCodes', 'md'] },
  { key: 'audit-plan', stage: 'stage1', registryKey: 'audit-plan', templateId: 5, title: 'Audit Plan', formNo: '04-5', defaultOn: true, fields: [] },
  { key: 'audit-meeting', stage: 'stage1', registryKey: 'audit-meeting', templateId: 2, title: 'Audit Meeting / Performa', formNo: '04-5', defaultOn: true, fields: [] },
  { key: 's1-plan-qms', stage: 'stage1', registryKey: 'form-04-5-stage-1-audit-plan-qms-9001', templateId: 12, title: 'Stage 1 Audit Plan – QMS 9001', formNo: '04-5', variantFor: 'Q', fields: PLAN_FIELDS },
  { key: 's1-plan-ems', stage: 'stage1', registryKey: 'form-04-5-stage-1-audit-plan-ems-14001', templateId: 28, title: 'Stage 1 Audit Plan – EMS 14001', formNo: '04-5', variantFor: 'E', fields: PLAN_FIELDS },
  { key: 's1-plan-ohs', stage: 'stage1', registryKey: 'form-04-5-stage-1-audit-plan-ohsms-45001', templateId: 11, title: 'Stage 1 Audit Plan – OH&S 45001', formNo: '04-5', variantFor: 'O', fields: PLAN_FIELDS },
  { key: 's1-plan-qms-ems', stage: 'stage1', registryKey: 'form-04-5-stage-1-audit-plan-qms-ems', templateId: 49, title: 'Stage 1 Audit Plan – QMS + EMS', formNo: '04-5', variantFor: 'QE', fields: PLAN_FIELDS },
  { key: 's1-plan-qms-ohs', stage: 'stage1', registryKey: 'form-04-5-stage-1-audit-plan-qms-ohs', templateId: 50, title: 'Stage 1 Audit Plan – QMS + OH&S', formNo: '04-5', variantFor: 'QO', fields: PLAN_FIELDS },
  { key: 's1-plan-ems-ohs', stage: 'stage1', registryKey: 'form-04-5-stage-1-audit-plan-ems-ohsm', templateId: 51, title: 'Stage 1 Audit Plan – EMS + OH&S', formNo: '04-5', variantFor: 'EO', fields: PLAN_FIELDS },
  { key: 's1-plan-ims', stage: 'stage1', registryKey: 'form-04-5-stage-1-audit-plan-IMS(qms,ems,oh&s)', templateId: 52, title: 'Stage 1 Audit Plan – IMS (QMS, EMS, OH&S)', formNo: '04-5', variantFor: 'QEO', fields: PLAN_FIELDS },
  { key: 's1-plan-ims-alt', stage: 'stage1', registryKey: 'form-04-5-stage-1-audit-plan-ims', templateId: 9, title: 'Stage 1 Audit Plan – IMS (alternative layout)', formNo: '04-5', fields: PLAN_FIELDS },
  { key: 's1-plan-blank', stage: 'stage1', registryKey: 'form-04-5-stage-1-audit-plan-blank', templateId: 53, title: 'Stage 1 Audit Plan – blank (other standards)', formNo: '04-5', variantFor: '', fields: PLAN_FIELDS },
  { key: 'scope-summary', stage: 'stage1', registryKey: 'scope-summary-report', templateId: 1, title: 'Scope Summary Report', defaultOn: true, fields: [] },
  { key: 'final-letter', stage: 'stage1', registryKey: 'final_company_info_letter', templateId: 44, title: 'Final Company Information Letter', defaultOn: true, fields: [] },
  { key: 'rules-regulations', stage: 'stage1', registryKey: 'rules-regulations', templateId: null, title: 'Rules & Regulations', fields: [] },

  // ───────────── Stage 2 ─────────────
  { key: 's2-plan-qms', stage: 'stage2', registryKey: 'form-04-5-stage-2-audit-plan-qms-9001', templateId: 55, title: 'Stage 2 Audit Plan – QMS 9001', formNo: '04-5', variantFor: 'Q', fields: PLAN_FIELDS },
  { key: 's2-plan-ems', stage: 'stage2', registryKey: 'form-04-5-stage-2-audit-plan-ems-14001', templateId: 56, title: 'Stage 2 Audit Plan – EMS 14001', formNo: '04-5', variantFor: 'E', fields: PLAN_FIELDS },
  { key: 's2-plan-ohs', stage: 'stage2', registryKey: 'form-04-5-stage-2-audit-plan-ohsms-45001', templateId: 57, title: 'Stage 2 Audit Plan – OH&S 45001', formNo: '04-5', variantFor: 'O', fields: PLAN_FIELDS },
  { key: 's2-plan-qms-ems', stage: 'stage2', registryKey: 'form-04-5-stage-2-audit-plan-qms-ems', templateId: 58, title: 'Stage 2 Audit Plan – QMS + EMS', formNo: '04-5', variantFor: 'QE', fields: PLAN_FIELDS },
  { key: 's2-plan-qms-ohs', stage: 'stage2', registryKey: 'form-04-5-stage-2-audit-plan-qms-ohs', templateId: 59, title: 'Stage 2 Audit Plan – QMS + OH&S', formNo: '04-5', variantFor: 'QO', fields: PLAN_FIELDS },
  { key: 's2-plan-ems-ohs', stage: 'stage2', registryKey: 'form-04-5-stage-2-audit-plan-ems-ohsm', templateId: 60, title: 'Stage 2 Audit Plan – EMS + OH&S', formNo: '04-5', variantFor: 'EO', fields: PLAN_FIELDS },
  { key: 's2-plan-ims', stage: 'stage2', registryKey: 'form-04-5-stage-2-audit-plan-IMS(qms,ems,oh&s)', templateId: 61, title: 'Stage 2 Audit Plan – IMS (QMS, EMS, OH&S)', formNo: '04-5', variantFor: 'QEO', fields: PLAN_FIELDS },
  { key: 's2-plan-blank', stage: 'stage2', registryKey: 'form-04-5-stage-2-audit-plan-blank', templateId: 54, title: 'Stage 2 Audit Plan – blank (other standards)', formNo: '04-5', variantFor: '', fields: PLAN_FIELDS },
  { key: 'objective-checklist', stage: 'stage2', registryKey: 'stage-2-audit-objective-checklist', templateId: 45, title: 'Audit Objective Checklist', formNo: '04-2-2', defaultOn: true, fields: ['docReview'] },
  { key: 'decision-sheet', stage: 'stage2', registryKey: 'stage-2-certification-requirement-decission-sheet', templateId: 46, title: 'Certification Requirement & Decision Sheet', formNo: '04-1 / 04-2 / 04-2-1', defaultOn: true, fields: ['naceEacCodes'] },
  { key: 'iso-checklist', stage: 'stage2', registryKey: 'stage-2-ISO 9001,14001,45001-checklist', templateId: 48, title: 'ISO 9001 / 14001 / 45001 Checklist', formNo: '04-3-5N', defaultOn: true, fields: [] },
  { key: 'surveillance-plan', stage: 'stage2', registryKey: 'stage-2-surv-plan-qms,ems & 45001', templateId: 47, title: 'Surveillance Plan (QMS, EMS & 45001)', formNo: '04-8-5I', defaultOn: true, fields: [] },
  { key: 'audit-meeting-s2', stage: 'stage2', registryKey: 'audit-meeting', templateId: 63, title: 'Audit Meeting', formNo: '04-5', defaultOn: true, fields: [] },
  { key: 'recommendation', stage: 'stage2', registryKey: 'form 07-2-3-recommendation', templateId: 64, title: 'Recommendation', formNo: '07-2-3', defaultOn: true, fields: ['approvedDate', 'docReview', 'naceEacCodes'] },
];

/** Standard name → Q / E / O. The umbrella "ISO 9001, 14001 & 45001" gives all three. */
export function stdKeysFor(names: string[]): StdKey[] {
  const out = new Set<StdKey>();
  for (const n of names.map((x) => String(x || ''))) {
    const all = /9001.*14001.*45001/.test(n);
    if (all || /\b9001\b/.test(n)) out.add('Q');
    if (all || /\b14001\b/.test(n)) out.add('E');
    if (all || /\b45001\b/.test(n)) out.add('O');
  }
  return (['Q', 'E', 'O'] as StdKey[]).filter((k) => out.has(k));
}

/** Forms ticked by default for this stage + standards. */
export function defaultFormKeys(stage: PackStage, keys: StdKey[]): string[] {
  const combo = keys.join('');
  return PACK_FORMS.filter((f) => {
    if (f.stage !== stage) return false;
    if (f.variantFor !== undefined) return f.variantFor === combo;
    if (f.forStd) return keys.includes(f.forStd) || (keys.length === 0 && f.forStd === 'Q');
    return !!f.defaultOn;
  }).map((f) => f.key);
}

/** Audit-schedule row stage text → default pack stage. */
export function packStageFor(auditType: string, auditStage: string): PackStage {
  const s = `${auditStage || ''}`.toLowerCase().replace(/\s+/g, '');
  if (s === 'stage1') return 'stage1';
  if (s === 'stage2') return 'stage2';
  return String(auditType || '').toUpperCase() === 'INITIAL' ? 'stage1' : 'stage2';
}

/** Standard name → job-code prefix (same table as JobsService.PREFIX_MAP, plus fallbacks for newer names). */
export function jobPrefixFor(name: string): string | null {
  const n = String(name || '');
  const exact: Record<string, string> = {
    'ISO 9001, 14001 & 45001': 'QMS_EMS_OHSMS',
    'ISO 9001': 'QMS',
    'ISO 9001:2015': 'QMS',
    'ISO 14001:2015': 'EMS',
    'ISO 45001:2018': 'OHSMS',
    'ISO 22000:2018': 'FSMS',
    'ISO 41001:2018': 'HALAL',
    'ISO22301:2019': 'ISO22301',
    'ISO50001:2018': 'ISO50001',
    'ISO29001:2020': 'ISO29001',
    'ISO 27001:2013': 'ISMS',
    'ISO 21001: 2018': 'ISO21001',
    HACCP: 'HACCP',
  };
  if (exact[n]) return exact[n];
  const rules: [RegExp, string][] = [
    [/9001.*14001.*45001/, 'QMS_EMS_OHSMS'],
    [/\b9001\b/, 'QMS'],
    [/\b14001\b/, 'EMS'],
    [/\b45001\b/, 'OHSMS'],
    [/\b22000\b/, 'FSMS'],
    [/\b27001\b/, 'ISMS'],
    [/22301/, 'ISO22301'],
    [/50001/, 'ISO50001'],
    [/29001/, 'ISO29001'],
    [/21001/, 'ISO21001'],
    [/13485/, 'ISO13485'],
    [/37001/, 'ISO37001'],
    [/9120/, 'ISO9120'],
    [/21500/, 'ISO21500'],
    [/haccp/i, 'HACCP'],
    [/halal|41001/i, 'HALAL'],
    [/gmp/i, 'GMP'],
  ];
  for (const [re, p] of rules) if (re.test(n)) return p;
  return null;
}

/** First numbers per prefix (same as JobsService.INITIAL_NUMBERS). */
export const JOB_INITIAL_NUMBERS: Record<string, number> = {
  QMS: 96148,
  EMS: 43138,
  OHSMS: 6129,
  FSMS: 168,
  HACCP: 140,
  ISMS: 7,
  ISO22000: 7,
  HALAL: 10,
  GMP: 13,
  ISO22301: 19,
  ISO50001: 8,
  ISO29001: 1,
  ISO9120: 1,
  ISO37001: 2,
  ISO21001: 1,
  ISO21500: 1,
  ISO13485: 4,
  HACAP: 1,
  QMS_EMS_OHSMS: 1,
};
