import type { DocumentTemplateMappingWithColumns } from '@/features/foundation/document-template/types';
import type { QuotationDocumentData } from '../types';
import type {
  RenderContext,
  RenderPolicy,
  ResolvedPages,
  ResolvedTemplate,
  RuntimeIssue,
  SectionRole,
} from './runtime-contracts';
import { SECTION_ORDER } from './runtime-contracts';

function buildDefaultPolicy(
  section: SectionRole,
  args?: { pages?: ResolvedPages; documentData?: QuotationDocumentData },
): RenderPolicy {
  switch (section) {
    case 'customer':
      return {
        section,
        enabled: true,
        required: true,
        visibleWhenEmpty: true,
      };
    case 'product_items':
      return {
        section,
        enabled: Boolean(args?.pages?.byRole.product_items?.length),
        required: false,
        visibleWhenEmpty: true,
      };
    case 'topics':
      return {
        section,
        enabled: true,
        required: true,
        visibleWhenEmpty: true,
      };
    default:
      return {
        section,
        enabled: false,
        required: false,
        visibleWhenEmpty: false,
      };
  }
}

export function resolveRenderPolicies(args?: {
  pages?: ResolvedPages;
  documentData?: QuotationDocumentData;
}): RenderPolicy[] {
  return SECTION_ORDER.map((section) => buildDefaultPolicy(section, args));
}

export function createRenderContext(args: {
  documentData: QuotationDocumentData;
  template: ResolvedTemplate;
  mappings: DocumentTemplateMappingWithColumns[];
  pages: ResolvedPages;
  policies: RenderPolicy[];
  issues?: RuntimeIssue[];
}): RenderContext {
  const policyBySection = new Map<SectionRole, RenderPolicy>(
    args.policies.map((policy) => [policy.section, policy]),
  );

  return {
    documentData: args.documentData,
    template: args.template,
    mappings: args.mappings,
    pages: args.pages,
    policies: [...args.policies],
    policyBySection,
    issues: [...(args.issues ?? [])],
  };
}
