import { exportInvoicePdfFromSlug } from '../../woocommerce/invoice/exportInvoicePdf';
import { getConfig } from './config';
import { showUpdateButtonLoader, hideUpdateButtonLoader } from './ui';
import { fetchInvoiceContext, uploadInvoicePdf, getAdminDesignEndpoint } from './api';

function getOrderIdFromPage(): number {
	const params = new URLSearchParams(window.location.search);
	const raw = params.get('id') || params.get('post') || '0';
	const n = parseInt(raw, 10);
	return Number.isFinite(n) && n > 0 ? n : 0;
}

export function initOrderCompleteIntercept(): void {
	const statusSelect = document.querySelector<HTMLSelectElement>('#order_status');
	if (!statusSelect) return;

	const form =
		document.querySelector<HTMLFormElement>('form#order') ||
		document.querySelector<HTMLFormElement>('#post');
	if (!form) return;

	form.addEventListener('submit', async (e) => {
		if (statusSelect.value !== 'wc-completed') return;

		const nonce = getConfig().nonce ?? '';
		const orderId = getOrderIdFromPage();
		if (!nonce || !orderId) return;

		e.preventDefault();

		const spinner = showUpdateButtonLoader();

		try {
			const ctx = await fetchInvoiceContext(orderId, nonce);

			if (ctx.isGenerated || !ctx.designSlug || ctx.generationMode === 'manual') {
				hideUpdateButtonLoader(spinner);
				form.submit();
				return;
			}

			// The PDF is generated BEFORE the form saves, so the server still
			// returns the old status (e.g. "processing").  Override order_status
			// with the value the admin has already selected in the dropdown so
			// the generated PDF reflects the new status ("completed" etc.).
			const pendingStatus = statusSelect.value.replace(/^wc-/, '');
			const mergeTagsWithNewStatus = {
				...ctx.mergeTags,
				order_status: pendingStatus,
			};

			const { blob } = await exportInvoicePdfFromSlug(
				ctx.designSlug,
				mergeTagsWithNewStatus,
				orderId,
				nonce,
				getAdminDesignEndpoint(orderId),
			);

			await uploadInvoicePdf(orderId, blob, nonce);
		} catch {
			// silent — form submits regardless
		} finally {
			hideUpdateButtonLoader(spinner);
			form.submit();
		}
	});
}
