import type {
  CompatibleTemplate,
  ResolvedPage,
  ResolvedPages,
  RuntimeIssue,
  SectionRole,
} from './runtime-contracts';
import { SINGLETON_SECTION_ROLES } from './runtime-contracts';

function createByRoleMap(): Partial<Record<SectionRole, ResolvedPage[]>> {
  return {};
}

export function resolveTemplatePages(
  compatibleTemplate: CompatibleTemplate,
): ResolvedPages {
  const byRole = createByRoleMap();
  const issues: RuntimeIssue[] = [...compatibleTemplate.issues];
  const all: ResolvedPage[] = compatibleTemplate.pages.map((page) => ({ ...page }));

  for (const page of all) {
    for (const role of page.roles) {
      const pages = byRole[role] ?? [];
      pages.push(page);
      byRole[role] = pages;
    }
  }

  for (const [role, pages] of Object.entries(byRole) as Array<
    [SectionRole, ResolvedPage[]]
  >) {
    if (!SINGLETON_SECTION_ROLES.has(role) || pages.length <= 1) {
      continue;
    }

    issues.push({
      code: 'DUPLICATE_MARKER',
      severity: 'error',
      message: 'PDF template resolves multiple singleton section pages.',
      details: {
        role,
        pageIndexes: pages.map((page) => page.pageIndex),
      },
    });
  }

  return {
    all,
    byRole,
    issues,
  };
}
