// @ts-check

/**
 * Prepare routes templates
 */
function tplRoutesPrepare(callback) {
  // TODO: maybe autogenerate laravel routes definitions?
  callback();
}

/**
 * Assemble routes templates
 */
function tplRoutesAssemble() {
  const gulp = require("gulp");
  const rename = require("gulp-rename");
  const { getRouteFileName } = require("../utils/route");
  const { join, frontend } = require("../paths");
  const { src, dest } = frontend;

  return gulp
    .src(join(src.routes, "**/*.{php,json}"), { base: src.routes })
    .pipe(
      rename((path) => {
        const isBlade = path.basename.endsWith(".blade");
        const isIndex = path.basename.startsWith("index");
        const filename = path.basename.replace(/\.blade$/, "");

        if (isIndex) {
          path.basename = getRouteFileName(path.dirname);
        } else {
          path.basename = getRouteFileName(path.dirname + "-" + filename);
        }
        if (isBlade) {
          path.basename += ".blade";
        }

        path.dirname = "";
      })
    )
    .pipe(gulp.dest(dest.routes));
}

/**
 * Collect subtasks in a single task that respect the gulp async lifecycle by
 * calling the callback on completion.
 */
module.exports = function tplRoutes(callback) {
  const gulp = require("gulp");
  return gulp.series(tplRoutesPrepare, tplRoutesAssemble)(callback);
};
