// @ts-check

/**
 * Create dummy files that are usually required to run the website locally,
 * wihout overwriting existing ones.
 */
function checkAutomatedPartials() {
  const gulp = require("gulp");
  const rename = require("gulp-rename");
  const header = require("gulp-header");
  const paths = require("../paths");
  const checker = require("@acanto/workflow-utils/checker");
  const { getHeaderAutogeneration } = require("../utils");
  const { filenames } = require("../config");
  const { dest } = paths.frontend;
  const opts = { overwrite: false };

  checker.filesExist(
    [
      { name: filenames.faviconsPartial, dest: dest.automated },
      { name: filenames.assetsHeadPartial, dest: dest.automated },
      { name: filenames.assetsBodyPartial, dest: dest.automated },
      { name: filenames.svgIconsPartial, dest: dest.automated },
    ],
    {
      willAutogenerate: true,
    }
  );

  // with `overwrite: false` we can safely create the files even if they already
  // exist, in that case we have just logged a warn anyway
  return gulp
    .src(paths.join(paths.self.templates, "dummy.blade.php"))
    .pipe(header(`{{-- ${getHeaderAutogeneration()} --}}\n\n`))
    .pipe(rename(filenames.faviconsPartial))
    .pipe(gulp.dest(dest.automated, opts))
    .pipe(rename(filenames.assetsHeadPartial))
    .pipe(gulp.dest(dest.automated, opts))
    .pipe(rename(filenames.assetsBodyPartial))
    .pipe(gulp.dest(dest.automated, opts))
    .pipe(rename(filenames.svgIconsPartial))
    .pipe(gulp.dest(dest.automated, opts));
}

/**
 * Check routes consistency
 */
async function checkRoutes(callback) {
  const { getCmsRoutes, checkRoutesConsistency } = require("../utils/route");

  if (!process.env.DEV_SKIP_CMS_ROUTES_CHECK) {
    const data = await getCmsRoutes();
    checkRoutesConsistency(data);
  }

  callback();
}

/**
 * Collect subtasks in a single task that respect the gulp async lifecycle by
 * calling the callback on completion.
 */
module.exports = function check(callback) {
  const gulp = require("gulp");

  return gulp.series(checkAutomatedPartials, checkRoutes)(callback);
};
