/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

'use strict';

const upath = require( 'upath' );
const { globSync } = require( 'glob' );
const fs = require( 'fs-extra' );

/**
 * Caches build files so that they can be reused. Only for local (dev==true flag) build.
 *
 * @param src
 * @param dst
 * @returns {boolean}
 */
module.exports = ( src, dst ) => {
	const sourcePaths = globSync( upath.join( src, '**', '*' ) ).map( path => upath.normalize( path ) );
	let result = false;

	for ( const p of sourcePaths ) {
		const strippedPath = p.replace( src, '' );
		const cachePath = upath.join( dst, strippedPath );

		if ( !fs.existsSync( cachePath ) ) {
			try {
				fs.copySync( p, cachePath );
			} catch {
				console.error( `Error when caching file ${ p } to ${ cachePath }` );
			}

			result = true;
		}

		const currentStats = fs.statSync( p );
		const cachedStats = fs.statSync( cachePath );

		if ( currentStats.size !== cachedStats.size || currentStats.mtime > cachedStats.mtime ) {
			try {
				fs.copySync( p, cachePath );
			} catch {
				console.error( `Error when caching file ${ p } to ${ cachePath }` );
			}

			// Some files have changed, return true to run webpack for example.
			result = true;
		}
	}

	return result;
};
