import sharp from 'sharp';
import { LoggingService } from './logService';
import Config from '#config';

process.on('message', async (payload: { file: Express.Multer.File; compressType: string; compressSize: string }) => {
	const logger = new LoggingService();
	const endProcess = ({
			startTime,
			...endPayload
		}: {
			startTime: number;
			statusCode: number;
			text: string;
			path?: any;
		}) => {
			// CQ-04: use structured logger instead of console.log
			logger
				.logInfoAsync(
					'compressService',
					`Worker ${process.pid} finished in ${(performance.now() - startTime).toFixed(1)}ms — ${endPayload.text}`,
					null,
				)
				.catch(() => {});
			// Format response so it fits the api response
			if (process.send) {
				process.send(endPayload);
			}
			// End process
			process.exit();
		},
		qualityFn = (compressSize: string) => {
			switch (compressSize) {
				case 'tablet':
					return 50;
				case 'mobile':
					return 10;
				case 'preload':
					return 1;
				default:
					return 90;
			}
		},
		{ compressType, file, compressSize } = payload,
		quality = qualityFn(compressSize),
		filename = file.filename.split('.'),
		startTime = performance.now();
	logger
		.logInfoAsync(
			'compressService',
			`Worker ${process.pid} compressing ${file.filename} (${compressType}, ${compressSize})`,
			null,
		)
		.catch(() => {});

	try {
		let compressedFilePath = '';
		switch (compressType) {
			case 'IMAGE':
				// Process image
				compressedFilePath = `${file.destination}/${filename[0]}_${compressSize}.webp`;

				await sharp(file.path)
					.toFormat('webp')
					.webp({ quality })
					.resize(compressSize == 'preload' ? 20 : null)
					.toFile(compressedFilePath);

				return endProcess({
					startTime,
					statusCode: 200,
					text: 'Upload và tối ưu thành công hình ảnh',
					path: {
						[compressSize]: `${Config.uploads.storageImagesPath}/${filename[0]}_${compressSize}.webp`,
					},
				});
			case 'VIDEO':
				// CQ-04: VIDEO compression is NOT implemented (ffmpeg dependency removed).
				// Return null to indicate compression not supported, so callers don't create variant records
				return endProcess({
					startTime,
					statusCode: 204,
					text: 'Video compression not supported',
					path: null,
				});
			default:
				// Return null for unsupported types to prevent variant creation
				return endProcess({
					startTime,
					statusCode: 204,
					text: 'File type not supported for compression',
					path: null,
				});
		}
	} catch (error) {
		await new LoggingService().logErrorAsync(
			'compressFileService',
			error instanceof Error ? error : new Error(String(error)),
			null,
		);
		return endProcess({
			statusCode: 500,
			text: error instanceof Error ? error.message : 'An unknown error occurred',
			startTime,
		});
	}
});
