/**
 * REST calls used by the wizard. Uploads use XMLHttpRequest directly
 * (instead of apiFetch) so we can report upload progress -- fetch() has no
 * upload progress event.
 */

import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';

export function listSuppliers() {
	return apiFetch( { path: '/emberprice/v1/suppliers' } );
}

export function createJob( { file, supplierId, supplierName, onProgress } ) {
	return new Promise( ( resolve, reject ) => {
		const formData = new FormData();
		formData.append( 'file', file );

		if ( supplierId ) {
			formData.append( 'supplier_id', supplierId );
		} else {
			formData.append( 'supplier_name', supplierName );
		}

		const xhr = new window.XMLHttpRequest();
		xhr.open( 'POST', `${ window.embpSettings.root }emberprice/v1/jobs` );
		xhr.setRequestHeader( 'X-WP-Nonce', window.embpSettings.nonce );

		xhr.upload.addEventListener( 'progress', ( event ) => {
			if ( event.lengthComputable && onProgress ) {
				onProgress(
					Math.round( ( event.loaded / event.total ) * 100 )
				);
			}
		} );

		xhr.addEventListener( 'load', () => {
			let data = null;

			try {
				data = JSON.parse( xhr.responseText );
			} catch ( parseError ) {
				reject( {
					message: __( 'Unexpected server response.', 'emberprice' ),
				} );
				return;
			}

			if ( xhr.status >= 200 && xhr.status < 300 ) {
				resolve( data );
			} else {
				reject( data );
			}
		} );

		xhr.addEventListener( 'error', () => {
			reject( {
				message: __( 'Network error while uploading.', 'emberprice' ),
			} );
		} );

		xhr.send( formData );
	} );
}

export function confirmMapping( jobId, columnMap, hasIva ) {
	return apiFetch( {
		path: `/emberprice/v1/jobs/${ jobId }/map`,
		method: 'POST',
		data: { column_map: columnMap, has_iva: hasIva },
	} );
}

export function getJob( jobId ) {
	return apiFetch( { path: `/emberprice/v1/jobs/${ jobId }` } );
}

export function matchJob( jobId, retry = false ) {
	return apiFetch( {
		path: `/emberprice/v1/jobs/${ jobId }/match`,
		method: 'POST',
		data: { retry },
	} );
}

export function getJobProgress( jobId ) {
	return apiFetch( { path: `/emberprice/v1/jobs/${ jobId }/progress` } );
}

export function getJobRows( jobId, { status, page } ) {
	const query = new URLSearchParams();

	if ( status ) {
		query.set( 'status', status );
	}

	query.set( 'page', page );

	return apiFetch( {
		path: `/emberprice/v1/jobs/${ jobId }/rows?${ query.toString() }`,
	} );
}

export function confirmRow( rowId ) {
	return apiFetch( {
		path: `/emberprice/v1/rows/${ rowId }/confirm`,
		method: 'POST',
	} );
}

export function rejectRow( rowId ) {
	return apiFetch( {
		path: `/emberprice/v1/rows/${ rowId }/reject`,
		method: 'POST',
	} );
}

export function assignRow( rowId, productId, variationId ) {
	return apiFetch( {
		path: `/emberprice/v1/rows/${ rowId }/assign`,
		method: 'POST',
		data: { product_id: productId, variation_id: variationId || undefined },
	} );
}

export function searchProducts( query ) {
	return apiFetch( {
		path: `/emberprice/v1/products/search?q=${ encodeURIComponent(
			query
		) }`,
	} );
}

export function updateSupplierRule( supplierId, defaultRule ) {
	return apiFetch( {
		path: `/emberprice/v1/suppliers/${ supplierId }`,
		method: 'PUT',
		data: { default_rule: defaultRule },
	} );
}

export function previewJob( jobId ) {
	return apiFetch( {
		path: `/emberprice/v1/jobs/${ jobId }/preview`,
		method: 'POST',
	} );
}

export function listJobs( page = 1, perPage = 20 ) {
	return apiFetch( {
		path: `/emberprice/v1/jobs?page=${ page }&per_page=${ perPage }`,
	} );
}

export function applyJob( jobId, retry = false ) {
	return apiFetch( {
		path: `/emberprice/v1/jobs/${ jobId }/apply`,
		method: 'POST',
		data: { retry },
	} );
}

export function rollbackJob( jobId, retry = false ) {
	return apiFetch( {
		path: `/emberprice/v1/jobs/${ jobId }/rollback`,
		method: 'POST',
		data: { retry },
	} );
}

export function exportJob( jobId ) {
	return apiFetch( { path: `/emberprice/v1/jobs/${ jobId }/export` } );
}

export function getLlmEstimate( jobId ) {
	return apiFetch( { path: `/emberprice/v1/jobs/${ jobId }/llm-estimate` } );
}

export function adjudicateJob( jobId ) {
	return apiFetch( {
		path: `/emberprice/v1/jobs/${ jobId }/adjudicate`,
		method: 'POST',
	} );
}

// Product categories: WooCommerce registers `product_cat` with REST support,
// so the core WP REST API already exposes it -- no need for our own route.
export function listProductCategories() {
	return apiFetch( {
		path: '/wp/v2/product_cat?per_page=100&orderby=name&order=asc',
	} );
}
