import { json } from '@sveltejs/kit';
import { TEBEX_PUBLIC_TOKEN } from '$env/static/private';

// Headless API uses a Public Token - this is SAFE to expose in frontend!
// Get yours from: https://creator.tebex.io/developers/api-keys
//const TEBEX_PUBLIC_TOKEN = import.meta.env.TEBEX_PUBLIC_TOKEN || process.env.TEBEX_PUBLIC_TOKEN || '11l0a-f41daf73e7c51551139bab611d51bb2640784301';

/**
 * Headless API Checkout Handler
 * 
 * This uses Tebex's Headless API which:
 * - Works with pre-created packages in your Tebex store
 * - Doesn't require special Checkout API approval
 * - Uses a public token (no authentication needed)
 * - Perfect for standard Minecraft stores
 * 
 * To use this:
 * 1. Create packages in your Tebex panel (Packages → Create Package)
 * 2. Get package IDs from the URL when editing packages
 * 3. Update the frontend tpi values to match your package IDs
 * 4. Set TEBEX_PUBLIC_TOKEN in your .env file
 */

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

		// Validate inputs
		if (!packageId || !mcusername) {
			return json(
				{ error: 'Missing required fields: packageId and mcusername' },
				{ status: 400 }
			);
		}

		// Validate Minecraft username (alphanumeric and underscore, 3-16 characters)
		const mcUsernameRegex = /^[a-zA-Z0-9_]{3,16}$/;
		if (!mcUsernameRegex.test(mcusername)) {
			return json(
				{ error: 'Invalid Minecraft username format' },
				{ status: 400 }
			);
		}

		if (!TEBEX_PUBLIC_TOKEN || TEBEX_PUBLIC_TOKEN === 'your-token-here') {
			console.error('TEBEX_PUBLIC_TOKEN not configured!');
			return json(
				{ error: 'Server configuration error. Please contact administrator.' },
				{ status: 500 }
			);
		}

		console.log('Creating basket for:', mcusername, 'Package:', packageId);

		// Step 1: Create a basket with the username
		const basketResponse = await fetch(
			`https://headless.tebex.io/api/accounts/${TEBEX_PUBLIC_TOKEN}/baskets`,
			{
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					// Return URLs
					complete_url: `${url.origin}/store?checkout=success`,
					cancel_url: `${url.origin}/store?checkout=cancel`,
					complete_auto_redirect: true,
					
					// Minecraft username - creates a username_id for package delivery
					username: mcusername,
					
					// Custom data - accessible in webhooks
					custom: {
						mcusername: mcusername,
						timestamp: new Date().toISOString()
					}
				})
			}
		);

		if (!basketResponse.ok) {
			const error = await basketResponse.json();
			console.error('Basket creation failed:', error);
			return json(
				{ 
					error: 'Failed to create basket', 
					details: error.errors || error 
				},
				{ status: basketResponse.status }
			);
		}

		const basketData = await basketResponse.json();
		const basket = basketData.data;
		const basketIdent = basket.ident;
		const usernameId = basket.username_id;

		console.log('✓ Basket created:', basketIdent);
		console.log('✓ Username ID:', usernameId);

		// Step 2: Add the package to the basket
		const packageResponse = await fetch(
			`https://headless.tebex.io/api/baskets/${basketIdent}/packages`,
			{
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					package_id: parseInt(packageId), // Must be a number
					quantity: 1,
					// Include username_id so package is delivered to correct player
					variable_data: {
						username_id: usernameId
					}
				})
			}
		);

		if (!packageResponse.ok) {
			const error = await packageResponse.json();
			console.error('Package add failed:', error);
			
			// Common error: package doesn't exist
			if (error.errors?.package_id) {
				return json(
					{ 
						error: 'Package not found. Make sure the package ID exists in your Tebex store.',
						packageId: packageId
					},
					{ status: 404 }
				);
			}
			
			return json(
				{ 
					error: 'Failed to add package', 
					details: error.errors || error 
				},
				{ status: packageResponse.status }
			);
		}

		const updatedBasketData = await packageResponse.json();
		const updatedBasket = updatedBasketData.data;

		console.log('✓ Package added successfully');
		console.log('✓ Checkout URL:', updatedBasket.links.checkout);

		// Step 3: Return the checkout URL
		return json({
			success: true,
			url: updatedBasket.links.checkout,
			ident: basketIdent,
			username: mcusername
		});

	} catch (error) {
		console.error('Checkout error:', error);
		return json(
			{ error: 'Internal server error', message: error.message },
			{ status: 500 }
		);
	}
}

/**
 * Optional: GET endpoint to verify basket status
 */
/** @type {import('./$types').RequestHandler} */
export async function GET({ url }) {
	const ident = url.searchParams.get('ident');
	
	if (!ident) {
		return json({ error: 'Missing basket identifier' }, { status: 400 });
	}

	try {
		const response = await fetch(
			`https://headless.tebex.io/api/accounts/${TEBEX_PUBLIC_TOKEN}/baskets/${ident}`
		);

		if (!response.ok) {
			return json({ error: 'Failed to fetch basket' }, { status: response.status });
		}

		const data = await response.json();
		return json(data.data);

	} catch (error) {
		console.error('Error fetching basket:', error);
		return json({ error: 'Internal server error' }, { status: 500 });
	}
}
