/**
 * Transak on-ramp adapter — wraps shared/transak.ts utilities
 * behind the OnrampProvider interface.
 */

import type { OnrampProvider, OnrampSessionRequest, OnrampSessionResult } from './onramp-provider';
import { createSecureWidgetUrl, extractRootDomain, getTransakApiKey } from '../../../shared/transak';

export class TransakOnrampAdapter implements OnrampProvider {
	id = 'transak' as const;
	name = 'Transak';

	isAvailable(): boolean {
		return !!getTransakApiKey();
	}

	async createSession(req: OnrampSessionRequest): Promise<OnrampSessionResult> {
		const apiKey = getTransakApiKey();
		if (!apiKey) throw new Error('Transak not configured');

		const widgetParams: Record<string, string> = {
			apiKey,
			referrerDomain: req.hostname ? extractRootDomain(req.hostname) : 'rspace.online',
			cryptoCurrencyCode: 'USDC',
			network: 'base',
			defaultCryptoCurrency: 'USDC',
			walletAddress: req.walletAddress,
			partnerOrderId: `user-${req.sessionId}`,
			email: req.email,
			themeColor: '6366f1',
			hideMenu: 'true',
		};
		if (req.fiatAmount > 0) {
			widgetParams.fiatAmount = String(req.fiatAmount);
			widgetParams.defaultFiatAmount = String(req.fiatAmount);
		}
		if (req.fiatCurrency) {
			widgetParams.fiatCurrency = req.fiatCurrency;
			widgetParams.defaultFiatCurrency = req.fiatCurrency;
		}
		if (req.returnUrl) widgetParams.redirectURL = req.returnUrl;

		const widgetUrl = await createSecureWidgetUrl(widgetParams);
		return { widgetUrl, provider: 'transak' };
	}
}
