const { PrismaClient } = require('@prisma/client');
const { Pool } = require('pg');
const { PrismaPg } = require('@prisma/adapter-pg');
const { Client } = require('ssh2');

const pool = new Pool({ connectionString: 'postgresql://saas_user:saas_secure_pass_2026@10.0.1.151:5432/saas_5651?schema=public' });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });

const host = '10.0.1.150';
const password = '02!Aug2013';

async function generateDeviceVpnConfig(macAddress, vpnIp) {
  return new Promise((resolve, reject) => {
    const conn = new Client();
    const clientName = `device_${macAddress.replace(/:/g, '')}`;
    
    const setupScript = `
      #!/bin/bash
      cd /etc/openvpn/server
      
      # 1. Create client certificate
      if [ ! -f "easy-rsa/pki/issued/${clientName}.crt" ]; then
        cd easy-rsa
        ./easyrsa --batch build-client-full "${clientName}" nopass
        cd ..
      fi

      # 2. Assign static IP
      mkdir -p ccd
      echo "ifconfig-push ${vpnIp} 255.255.255.0" > "ccd/${clientName}"

      echo "SUCCESS: VPN Config generated for ${clientName} with IP ${vpnIp}"
    `;

    conn.on('ready', () => {
      conn.exec(setupScript, (err, stream) => {
        if (err) return reject(err);
        stream.on('close', (code) => {
          conn.end();
          if (code === 0) resolve(true);
          else reject(new Error('Script failed with code ' + code));
        }).on('data', data => console.log('STDOUT: ' + data))
          .stderr.on('data', data => console.error('STDERR: ' + data));
      });
    }).connect({ host, port: 22, username: 'root', password, readyTimeout: 10000 });
  });
}

async function runTest() {
  console.log('--- Starting Test: SaaS E2E Tenant & Device Creation ---');
  
  console.log('1. Creating new Tenant: "Test Hotel A.S."');
  const tenant = await prisma.tenant.create({ data: { name: 'Test Hotel A.S.' } });
  
  console.log('2. Allocated VPN IP for new device: 10.10.0.1');
  const mac = '00:11:22:33:44:55';
  await prisma.device.create({
    data: {
      tenantId: tenant.id,
      name: 'Test Hotel Gateway',
      macAddress: mac,
      vpnIp: '10.10.0.1'
    }
  });

  console.log('3. Connecting to VPN Server (10.0.1.150) to generate config...');
  await generateDeviceVpnConfig(mac, '10.10.0.1');
  
  console.log('--- Test Completed ---');
}

runTest().catch(console.error).finally(() => prisma.$disconnect());
