/**
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

const path = require('path');
const readFileSync = require('fs').readFileSync;
const {getTOC, insertTOC} = require('../toc');
const {extractMetadata} = require('../../server/metadataUtils');

const getTOCmd = readFileSync(
  path.join(__dirname, '__fixtures__', 'getTOC.md'),
  'utf8',
);

const insertTOCmd = readFileSync(
  path.join(__dirname, '__fixtures__', 'insertTOC.md'),
  'utf8',
);

describe('getTOC', () => {
  test('with defaults', () => {
    const headings = getTOC(getTOCmd);
    const headingsJson = JSON.stringify(headings);

    expect(headings).toMatchSnapshot();
    expect(headingsJson).toContain('bar-8'); // maximum unique bar index is 8
    expect(headingsJson).not.toContain('4th level headings');
  });

  test('with custom heading levels', () => {
    const headings = getTOC(getTOCmd, 'h2', ['h3', 'h4']);
    const headingsJson = JSON.stringify(headings);

    expect(headings).toMatchSnapshot();
    expect(headingsJson).toContain('bar-8'); // maximum unique bar index is 8
    expect(headingsJson).toContain('4th level headings');
  });
});

describe('insertTOC', () => {
  test('null or undefined content', () => {
    expect(insertTOC(null)).toBeNull();
    expect(insertTOC(undefined)).toBeUndefined();
  });

  test('AUTOGENERATED_TABLE_OF_CONTENTS does not exist', () => {
    const rawContent = extractMetadata(getTOCmd).rawContent;
    expect(insertTOC(rawContent)).toMatchSnapshot();
    expect(insertTOC(rawContent)).toEqual(rawContent);
  });

  test('AUTOGENERATED_TABLE_OF_CONTENTS exists', () => {
    const rawContent = extractMetadata(insertTOCmd).rawContent;
    expect(insertTOC(rawContent)).toMatchSnapshot();
    expect(insertTOC(rawContent)).not.toEqual(rawContent);
  });
});
