import crypto from 'crypto';
import fs from 'fs';

// Generate EC key pair with curve prime256v1 (P-256) as required by Apple
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
  namedCurve: 'prime256v1',
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
});

console.log("=== NEUER PUBLIC KEY (FÜR APPLE SEARCH ADS) ===");
console.log(publicKey);

// Update .env.local with the new private key
const envPath = '.env.local';
let envContent = fs.readFileSync(envPath, 'utf8');

// Replace or set APPLE_SEARCH_ADS_PRIVATE_KEY
const cleanPrivateKey = privateKey.replace(/\r\n/g, '\n');
const formattedPrivateKey = `APPLE_SEARCH_ADS_PRIVATE_KEY="${cleanPrivateKey.replace(/\n/g, '\\n')}"`;

if (envContent.includes('APPLE_SEARCH_ADS_PRIVATE_KEY=')) {
  envContent = envContent.replace(/APPLE_SEARCH_ADS_PRIVATE_KEY=.*/g, formattedPrivateKey);
} else {
  envContent += `\n${formattedPrivateKey}\n`;
}

// Update public key in .env.local too
const formattedPublicKey = `APPLE_SEARCH_ADS_PUBLIC_KEY="${publicKey.replace(/\r\n/g, '\n').replace(/\n/g, '\\n')}"`;
if (envContent.includes('APPLE_SEARCH_ADS_PUBLIC_KEY=')) {
  envContent = envContent.replace(/APPLE_SEARCH_ADS_PUBLIC_KEY=.*/g, formattedPublicKey);
} else {
  envContent += `\n${formattedPublicKey}\n`;
}

fs.writeFileSync(envPath, envContent);
console.log("\n-> Private Key wurde automatisch in .env.local gespeichert!");
