import { exec } from 'child_process';
import chokidar from 'chokidar';
import nodemon from 'nodemon';

const nodeEnv = process.env.NODE_ENV || 'dev_stage';
const childEnv = { ...process.env, NODE_ENV: nodeEnv };

function runOnAdd(label: string, dir: string, script: string): void {
  chokidar
    .watch(dir, { persistent: true, ignoreInitial: true })
    .on('add', (filePath) => {
      console.log(`[DEBUG] New ${label} file: ${filePath}`);
      exec(script, { env: childEnv }, (error, stdout, stderr) => {
        console.log(stdout);
        if (error) {
          console.error(stderr);
        }
      });
    });
}

runOnAdd('migration', './src/db/migrations', 'npm run db:migrate');
runOnAdd('seed', './src/db/seeders', 'npm run db:seed');

nodemon({
  script: './src/index.ts',
  exec: 'tsx',
  ext: 'ts,js,json',
  env: childEnv,
  ignore: ['./src/db/migrations', './src/db/seeders'],
  delay: '500',
});

nodemon.on('start', () => {
  console.log('Nodemon started');
});

nodemon.on('restart', (files) => {
  console.log('Nodemon restarted due to changes in:', files);
});
