import { json } from '@sveltejs/kit';

/**
 * Tebex Webhook Handler
 * 
 * This endpoint receives webhook notifications from Tebex when payments are completed,
 * refunded, or charged back.
 * 
 * Setup in Tebex:
 * 1. Go to Developers → Webhooks in your Tebex Creator Panel
 * 2. Add webhook URL: https://yoursite.com/api/webhooks/tebex
 * 3. Enable events: payment.completed, payment.refunded
 * 
 * Security: For production, implement webhook signature verification
 */

/** @type {import('./$types').RequestHandler} */
export async function POST({ request }) {
	try {
		const payload = await request.json();

		console.log('Received Tebex webhook:', payload.type);

		// Handle different webhook types
		switch (payload.type) {
			case 'payment.completed':
				await handlePaymentCompleted(payload);
				break;

			case 'payment.refunded':
				await handlePaymentRefunded(payload);
				break;

			case 'payment.disputed':
				await handlePaymentDisputed(payload);
				break;

			default:
				console.log('Unhandled webhook type:', payload.type);
		}

		// Always return 200 OK to acknowledge receipt
		return json({ received: true }, { status: 200 });

	} catch (error) {
		console.error('Webhook processing error:', error);
		// Still return 200 to prevent Tebex from retrying
		return json({ error: 'Processing error' }, { status: 200 });
	}
}

/**
 * Handle completed payment
 */
async function handlePaymentCompleted(payload) {
	console.log('Payment completed:', payload.payment_id);

	// Extract custom data (including mcusername)
	const mcusername = payload.custom?.mcusername;
	const timestamp = payload.custom?.timestamp;

	// Extract purchase details
	const products = payload.products || [];
	const customer = payload.customer || {};
	const payment = payload.payment || {};

	console.log('Customer:', customer.email);
	console.log('Minecraft Username:', mcusername);
	console.log('Products purchased:', products.map(p => p.name).join(', '));

	// Process each product
	for (const product of products) {
		await processPurchase({
			mcusername,
			productName: product.name,
			productId: product.id,
			quantity: product.quantity,
			price: product.price,
			paymentId: payment.id,
			transactionId: payment.gateway_id,
			customerEmail: customer.email
		});
	}
}

/**
 * Handle refunded payment
 */
async function handlePaymentRefunded(payload) {
	console.log('Payment refunded:', payload.payment_id);

	const mcusername = payload.custom?.mcusername;
	const products = payload.products || [];

	// Revoke benefits for each product
	for (const product of products) {
		await revokePurchase({
			mcusername,
			productName: product.name,
			reason: 'refund'
		});
	}
}

/**
 * Handle disputed payment (chargeback)
 */
async function handlePaymentDisputed(payload) {
	console.log('Payment disputed:', payload.payment_id);

	const mcusername = payload.custom?.mcusername;
	const products = payload.products || [];

	// Revoke benefits and flag account
	for (const product of products) {
		await revokePurchase({
			mcusername,
			productName: product.name,
			reason: 'chargeback'
		});
	}
}

/**
 * Process a purchase - give player their items/rank
 * 
 * IMPORTANT: Implement this based on your game server integration
 */
async function processPurchase(data) {
	console.log('Processing purchase for', data.mcusername);

	// TODO: Implement your game server integration here
	// Options:
	// 1. Send command via RCON
	// 2. Call your game server API
	// 3. Update database that game server reads
	// 4. Use Tebex plugin on game server
	// 5. Queue for batch processing

	// Example: Send to game server API
	/*
	try {
		await fetch('https://your-game-server.com/api/purchase', {
			method: 'POST',
			headers: { 
				'Content-Type': 'application/json',
				'Authorization': 'Bearer YOUR_SERVER_API_KEY'
			},
			body: JSON.stringify({
				username: data.mcusername,
				product: data.productName,
				transactionId: data.transactionId
			})
		});
	} catch (error) {
		console.error('Failed to deliver purchase:', error);
		// Log to monitoring system, retry queue, etc.
	}
	*/

	// Example: Store in database for game server to poll
	/*
	await db.pendingPurchases.create({
		minecraft_username: data.mcusername,
		product_name: data.productName,
		product_id: data.productId,
		transaction_id: data.transactionId,
		processed: false,
		created_at: new Date()
	});
	*/

	console.log('✓ Purchase processed:', {
		username: data.mcusername,
		product: data.productName
	});
}

/**
 * Revoke a purchase - remove player's items/rank
 */
async function revokePurchase(data) {
	console.log('Revoking purchase for', data.mcusername, 'reason:', data.reason);

	// TODO: Implement revocation logic
	// Similar to processPurchase but in reverse

	console.log('✓ Purchase revoked:', {
		username: data.mcusername,
		product: data.productName,
		reason: data.reason
	});
}

// Optional: Verify webhook signature for security
// Tebex signs webhooks with a secret key
function verifyWebhookSignature(request, secret) {
	// Implementation depends on Tebex's signing method
	// Check Tebex documentation for latest signature verification
	return true; // Placeholder
}

/**
 * Example webhook payload structure:
 * 
 * {
 *   "type": "payment.completed",
 *   "payment_id": "tbx-12345",
 *   "payment": {
 *     "id": "tbx-12345",
 *     "amount": 9.99,
 *     "currency": "USD",
 *     "gateway_id": "ch_xxx",
 *     "status": "complete",
 *     "created_at": "2024-01-01T00:00:00Z"
 *   },
 *   "customer": {
 *     "email": "[email protected]",
 *     "first_name": "John",
 *     "last_name": "Doe"
 *   },
 *   "products": [
 *     {
 *       "id": 7258582,
 *       "name": "VIP Rank",
 *       "quantity": 1,
 *       "price": 9.99
 *     }
 *   ],
 *   "custom": {
 *     "mcusername": "playerName123",
 *     "timestamp": "2024-01-01T00:00:00.000Z"
 *   }
 * }
 */
