import { useServerSdk } from "../hooks";

/**
 * H5版本的Stripe支付服务
 */
export class PaymentService {
    /**
     * 发起支付
     * @param templateCode 模板代码
     * @param imageUrl 图片URL
     */
    async pay(templateCode: string, imageUrl: string): Promise<void> {
        try {
            const sdk = useServerSdk();
            const { hostname, protocol, port } = window.location;
            let baseUrl = `${protocol}//${hostname}`;
            if (hostname === 'localhost') {
                baseUrl = `${protocol}//${hostname}:${port}`;
            }
            const cbUrl = `${baseUrl}`;

            const response = await sdk.payTemplateCode(templateCode, imageUrl, cbUrl);

            if (response.url) {
                // 跳转到Stripe支付页面
                window.location.href = response.url;
                return;
            }

            throw new Error(`支付错误: ${JSON.stringify(response)}`);
        } catch (error) {
            console.error('支付失败:', error);
            throw error;
        }
    }

    /**
     * 处理支付成功回调
     * @param sessionId Stripe会话ID
     * @param paymentId 内部支付ID
     */
    async handlePaymentSuccess(sessionId: string, paymentId: string) {
        try {
            const sdk = useServerSdk();
            return await sdk.handlePaymentSuccess(sessionId, paymentId);
        } catch (error) {
            console.error('处理支付成功回调失败:', error);
            throw error;
        }
    }

    /**
     * 处理支付取消
     * @param sessionId Stripe会话ID
     * @param paymentId 内部支付ID
     */
    async handlePaymentCancel(sessionId: string, paymentId: string) {
        try {
            const sdk = useServerSdk();
            return await sdk.handlePaymentCancel(sessionId, paymentId);
        } catch (error) {
            console.error('处理支付取消失败:', error);
            throw error;
        }
    }

    /**
     * 获取支付历史
     * @param userId 用户ID
     */
    async getPaymentHistory(userId: string) {
        try {
            const sdk = useServerSdk();
            return await sdk.getPaymentHistory(userId);
        } catch (error) {
            console.error('获取支付历史失败:', error);
            throw error;
        }
    }
}

// 导出单例实例
export const paymentService = new PaymentService();
