/**
 * Script to fix Razorpay credentials encryption
 * Run with: node scripts/fixRazorpayCredentials.js
 */

require('dotenv').config();
const mongoose = require('mongoose');
const crypto = require('crypto');

// Get SECRET_KEY from environment
const ENCRYPTION_KEY = process.env.SECRET_KEY;

if (!ENCRYPTION_KEY || ENCRYPTION_KEY.length !== 64) {
    console.error("❌ SECRET_KEY must be a 64-character hex string in .env");
    process.exit(1);
}

function encrypt(text) {
    if (!text) return null;
    const keyBuffer = Buffer.from(ENCRYPTION_KEY, 'hex');
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv("aes-256-cbc", keyBuffer, iv);
    let encrypted = cipher.update(text, 'utf8');
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return iv.toString("hex") + ":" + encrypted.toString("hex");
}

async function fixCredentials() {
    try {
        console.log("Connecting to MongoDB...");
        await mongoose.connect(process.env.MONGODB_URI);
        console.log("✅ Connected to MongoDB");

        const Setting = mongoose.connection.collection('settings');

        // Get current settings
        const settings = await Setting.findOne({});

        if (!settings) {
            console.log("❌ No settings document found!");
            process.exit(1);
        }

        console.log("\n📋 Current Razorpay Configuration:");
        console.log("   Enabled:", settings.paymentGateways?.razorpay?.enabled);
        console.log("   KeyId:", settings.paymentGateways?.razorpay?.keyId);
        console.log("   SecretKey (encrypted):", settings.paymentGateways?.razorpay?.secretKey?.substring(0, 30) + "...");

        // ==========================================
        // Razorpay Credentials
        // ==========================================
        const RAZORPAY_SECRET_KEY = "5dHZnG5WoNJT82vOAiY7If4Y";
        const RAZORPAY_KEY_ID = "rzp_test_S6Q91Wjiyrs9mC";

        if (RAZORPAY_SECRET_KEY === "YOUR_ACTUAL_RAZORPAY_SECRET_KEY_HERE") {
            console.log("\n⚠️  Please edit this script and replace 'YOUR_ACTUAL_RAZORPAY_SECRET_KEY_HERE'");
            console.log("   with your actual Razorpay secret key from the Razorpay Dashboard.");
            console.log("   Location: https://dashboard.razorpay.com/app/website-app-settings/api-keys");
            process.exit(1);
        }

        // Encrypt the secret key
        const encryptedSecretKey = encrypt(RAZORPAY_SECRET_KEY);
        console.log("\n🔐 New encrypted secret key:", encryptedSecretKey.substring(0, 30) + "...");

        // Update the database
        await Setting.updateOne(
            { _id: settings._id },
            {
                $set: {
                    "paymentGateways.razorpay.keyId": RAZORPAY_KEY_ID.trim(),
                    "paymentGateways.razorpay.secretKey": encryptedSecretKey,
                    "paymentGateways.razorpay.enabled": true
                }
            }
        );

        console.log("\n✅ Razorpay credentials updated successfully!");
        console.log("   KeyId:", RAZORPAY_KEY_ID.trim());
        console.log("   SecretKey: [encrypted with current SECRET_KEY]");

        console.log("\n🔄 Please restart your backend server and try the payment API again.");

    } catch (error) {
        console.error("❌ Error:", error.message);
    } finally {
        await mongoose.disconnect();
        process.exit(0);
    }
}

fixCredentials();
