text: // @flow
  import markdownTable from 'markdown-table'
  
  import type { ReportSpec, FilesMetricsMap } from './config'
  
  import { FILES_SUM_METRIC_KEY } from './config'
  
  const metricsFor = (metricKeys: string[], record: Object) =>
    metricKeys.map(metric => record[metric] || '-')
  
  export const markdownAllTable = (specMetricKeys: string[], all: Object) => {
    const metricKeys = [FILES_SUM_METRIC_KEY, ...specMetricKeys]
  
    const headers = metricKeys
  
    const rows = metricsFor(metricKeys, all)
  
    return markdownTable([headers, rows])
  }
  
  export const markdownOwnersTable = (
    specMetricKeys: string[],
    ownerSum: Object,
  ) => {
    const metricKeys = [FILES_SUM_METRIC_KEY, ...specMetricKeys]
  
    const headers = ['owner', ...metricKeys]
  
    const rows = Object.keys(ownerSum).map(owner => [
      owner,
      ...metricsFor(metricKeys, ownerSum[owner]),
    ])
  
    return markdownTable([headers, ...rows])
  }
  
  export const markdownFileTable = (
    metricKeys: string[],
    eachFile: FilesMetricsMap,
  ) => {
    const headers = ['filename', ...metricKeys]
  
    const rows = Object.keys(eachFile).map(filename => [
      filename,
      ...metricsFor(metricKeys, eachFile[filename]),
    ])
  
    return markdownTable([headers, ...rows])
  }
  
  /**
   * Format the report as Markdown text
   */
  export const formatReport = (reportSpec: ReportSpec, report: *) => {
    const specMetricKeys = [
      ...Object.keys(reportSpec.regexpMetrics || {}),
      ...Object.keys(reportSpec.eslintFlags || {}),
    ]
  
    const content = [
      'This report was autogenerated by code-owners-report.',
      '## All files',
      markdownAllTable(specMetricKeys, report.allSum),
      '## By owner (non-exclusive)',
      report.ownerSum
        ? markdownOwnersTable(specMetricKeys, report.ownerSum)
        : 'Missing CODEOWNERS',
      '## Each file',
      markdownFileTable(['owners', ...specMetricKeys], report.eachFile),
      '\n',
    ].join('\n\n')
  
    return content
  }
  