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

'use strict';

const sass = require( 'sass' );
const fs = require( 'fs-extra' );
const upath = require( 'upath' );

module.exports = ( src, dst ) => {
	return new Promise( ( resolve, reject ) => {
		const options = {
			file: src,
			outputStyle: 'compressed',
			importer( url, file, done ) {
				// In case of import from the `themes/umberto/src` directory.
				const themeMatch = url && url.match( /@([^/]+)\/(.+)/ );

				if ( themeMatch ) {
					const [ , theme, remainingPath ] = themeMatch;
					const filePath = upath.join( __dirname, '../../themes/umberto/src', theme, 'css', remainingPath );

					if ( fs.existsSync( filePath ) ) {
						return done( { file: filePath } );
					}
				}

				// In case of an import from the `node_modules` directory.
				if ( url.startsWith( '~' ) ) {
					// Resolve the path regarding the current working directory.
					const absolutePath = require.resolve( url.substr( 1 ) );

					return fs.readFile( absolutePath, 'utf-8', ( err, data ) => {
						if ( err ) {
							return done( err );
						}

						return done( {
							contents: data
						} );
					} );
				}

				// Import a local file (a relative path).
				const directory = upath.dirname( file );

				// Replace "directory/filename" with "directory/_filename.scss".
				const fileName = url.replace( /(.+)(?:\/(.+))$/, ( match, dirName, fileName ) => {
					return dirName + '/_' + fileName + '.scss';
				} );

				return done( {
					file: upath.join( directory, fileName )
				} );
			}
		};

		sass.render( options, ( err, result ) => {
			if ( err ) {
				return reject( err );
			}

			fs.mkdirsSync( upath.dirname( dst ) );
			fs.writeFile( upath.resolve( dst ), result.css.toString( 'utf-8' ), err => {
				if ( err ) {
					return reject( err );
				}

				return resolve( true );
			} );
		} );
	} );
};
