export default async function handler(req, res) {
	if (req.method !== "GET") {
		return res.status(405).json({ success: false, error: "Method not allowed" });
	}

	const { sku } = req.query;

	if (!sku) {
		return res.status(400).json({ success: false, error: "SKU lipsă" });
	}

	try {
		const response = await fetch("https://easy-sales.com/feed/445/975393179/okazii.xml");
		const xmlText = await response.text();

		const auctionRegex = /<AUCTION>([\s\S]*?)<\/AUCTION>/g;
		let match;

          const sku = (req.query.sku || "").trim();

		while ((match = auctionRegex.exec(xmlText)) !== null) {
			const block = match[1];
			const skuMatch = block.match(/<SKU>([^<]*)<\/SKU>/);

			if (skuMatch && skuMatch[1].replace(/\s+/g, '') === sku.replace(/\s+/g, '')) {
				const discountMatch = block.match(/<DISCOUNT_PRICE>(.*?)<\/DISCOUNT_PRICE>/);
				const priceMatch = block.match(/<PRICE>(.*?)<\/PRICE>/);
				const titleMatch = block.match(/<TITLE>(.*?)<\/TITLE>/);

				const price = parseFloat(priceMatch?.[1] || 0);
				const discountPrice = parseFloat(discountMatch?.[1] || 0);
				const finalPrice = discountPrice > 0 && discountPrice < price ? discountPrice : price;

				return res.status(200).json({
					success: true,
					data: {
						price: finalPrice,
						originalPrice: price,
						title: titleMatch?.[1] || "",
						sku,
					},
				});
			}
		}

          const allSkus = [];
const debugRegex = /<AUCTION>([\s\S]*?)<\/AUCTION>/g;
let debugMatch;
while ((debugMatch = debugRegex.exec(xmlText)) !== null) {
    const skuM = debugMatch[1].match(/<SKU>([^<]*)<\/SKU>/);
    if (skuM) allSkus.push(skuM[1].trim());
}
return res.status(404).json({ 
    success: false, 
    error: "Produsul nu a fost găsit", 
    skuCautat: sku,
    totalProduseFeed: allSkus.length,
    existaInFeed: allSkus.includes(sku),
    toateSkurile: allSkus // vezi tot feed-ul
});

		return res.status(404).json({ success: false, error: "Produsul nu a fost găsit în feed-ul DEPOX" });
	} catch (err) {
		console.error("DEPOX feed error:", err);
		return res.status(500).json({ success: false, error: "Eroare la accesarea feed-ului DEPOX" });
	}
}
