import { PrismaClient } from '@prisma/client';
import { VpnService } from './src/services/VpnService';

const prisma = new PrismaClient();
const vpnService = new VpnService();

async function runTest() {
  console.log('--- Starting Test: SaaS E2E Tenant & Device Creation ---');
  
  // 1. Create a Tenant
  console.log('1. Creating new Tenant: "Test Hotel A.S."');
  const tenant = await prisma.tenant.create({
    data: { name: 'Test Hotel A.S.' }
  });
  console.log(`   Tenant created with ID: ${tenant.id}`);

  // 2. Figure out VPN IP
  const baseIp = '10.10.0.';
  const lastDevice = await prisma.device.findFirst({
    where: { vpnIp: { startsWith: baseIp } },
    orderBy: { vpnIp: 'desc' }
  });
  
  let nextVpnIp = '10.10.0.1';
  if (lastDevice && lastDevice.vpnIp) {
    const lastOctet = parseInt(lastDevice.vpnIp.split('.')[3], 10);
    nextVpnIp = `${baseIp}${lastOctet + 1}`;
  }
  console.log(`2. Allocated VPN IP for new device: ${nextVpnIp}`);

  // 3. Create Device
  console.log('3. Registering OPNsense device...');
  const mac = '00:11:22:33:44:55';
  const device = await prisma.device.create({
    data: {
      tenantId: tenant.id,
      name: 'Test Hotel Gateway',
      macAddress: mac,
      vpnIp: nextVpnIp,
      opnsenseUrl: 'https://192.168.1.1',
      apiKey: 'testkey',
      apiSecret: 'testsecret'
    }
  });
  console.log(`   Device registered successfully with MAC: ${mac}`);

  // 4. Trigger VPN Generation
  console.log('4. Connecting to VPN Server (10.0.1.150) via SSH to generate .ovpn config...');
  try {
    await vpnService.generateDeviceVpnConfig(mac, nextVpnIp);
    console.log('   SUCCESS! .ovpn file and ccd config created on VPN server.');
  } catch (e: any) {
    console.error('   FAILED to generate VPN config:', e.message);
  }

  console.log('--- Test Completed ---');
}

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