const { chokidar, signale, createDebug } = require('@umijs/utils');
const utils = require('./util');

const debug = createDebug('preset-build-in:mock:createMiddleware');

function createMiddleware(opts) {
  const { mockData, mockWatcherPaths, updateMockData } = opts;
  let data = mockData;
  const errors = [];
  debug('mockWatcherPaths', mockWatcherPaths);
  const watcher = chokidar.watch(mockWatcherPaths, {
    ignoreInitial: true,
  });
  watcher
    .on('ready', () => debug('Initial scan complete. Ready for changes'))
    .on('all', async (event, file) => {
      debug(`[${event}] ${file}, reload mock data`);
      errors.splice(0, errors.length);
      utils.cleanRequireCache(mockWatcherPaths);

      // refresh data
      // eslint-disable-next-line no-const-assign
      data = await updateMockData().mockData;
      if (!errors.length) {
        signale.success(`Mock files parse success`);
      }
    });
  process.once('SIGINT', async () => {
    await watcher.close();
  });
  return {
    middleware: (req, res, next) => {
      const match = data && utils.matchMock(req, data);
      if (match) {
        return match.handler(req, res, next);
      }
      return next();
    },
  };
}
module.exports = createMiddleware
