/**
 * Razorpay SDK error helper.
 *
 * The Razorpay node SDK rejects with an object shaped like:
 *   { statusCode: 401, error: { code: 'BAD_REQUEST_ERROR', description: 'Authentication failed', ... } }
 * (or sometimes a plain Error for network failures). Without handling, these
 * propagate as opaque HTTP 500s that hide the real reason (bad keys, etc.).
 *
 * extractRazorpayErrorMessage pulls out a human-readable reason so callers can
 * log it and return an actionable message to the client.
 */
export function extractRazorpayErrorMessage(err: any): string {
    if (!err) return 'Unknown payment gateway error';
    // Razorpay structured error
    const desc = err?.error?.description || err?.description;
    if (typeof desc === 'string' && desc.trim()) return desc.trim();
    // Razorpay sometimes nests differently
    const code = err?.error?.code || err?.code;
    if (typeof err?.message === 'string' && err.message.trim()) {
        return code ? `${err.message} (${code})` : err.message;
    }
    if (typeof code === 'string') return code;
    try {
        return JSON.stringify(err?.error || err);
    } catch {
        return 'Unknown payment gateway error';
    }
}

/**
 * True when the Razorpay error indicates an authentication / credential problem
 * (so we can tell the admin to re-check their keys rather than blame the network).
 */
export function isRazorpayAuthError(err: any): boolean {
    const status = err?.statusCode ?? err?.status;
    const desc = (err?.error?.description || err?.description || err?.message || '').toLowerCase();
    return status === 401 || desc.includes('authentication') || desc.includes('key_id') || desc.includes('api key');
}
