const gulp = require('gulp');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const clean = require('gulp-clean');
const sourcemaps = require('gulp-sourcemaps');

const paths = {
    js: [
        'js/custom-ui-settings/module.js',
        'js/custom-ui-settings/services/*.js',
        'js/custom-ui-settings/sections/*.js',
        'js/custom-ui-settings/directives/*.js',
    ],
    dest: 'js/'
};

// Clean task
gulp.task('clean', function() {
    return gulp.src('js/app.bundle*', { read: false, allowEmpty: true })
        .pipe(clean());
});


// Bundle with source maps for debugging
gulp.task('bundle-app-dev', function() {
    return gulp.src(paths.js, { base: 'js' }) // Set base to 'js' to preserve paths
        .pipe(sourcemaps.init())
        .pipe(concat('app.bundle.js'))
        .pipe(sourcemaps.write()) // Write source maps to the same directory
        .pipe(gulp.dest(paths.dest));
});

// Production bundle (minified, no source maps)
// Building from original source files, not from bundled files
gulp.task('bundle-app-prod', function() {
    return gulp.src(paths.js)  // Using the same source files as dev
        .pipe(concat('app.bundle.min.js'))  // Concatenate directly to min.js
        .pipe(uglify({
            mangle: false,
            compress: {
                keep_fnames: true,
                keep_fargs: true
            }
        }))
        .pipe(gulp.dest(paths.dest));
});

// Development task
gulp.task('dev', gulp.series('clean', 'bundle-app-dev'));

// Production task
gulp.task('prod', gulp.series('clean', 'bundle-app-prod'));