// [TSM.ID].[11031972] — All Rights Reserved. Proprietary & Confidential.
const { drizzle } = require('drizzle-orm/postgres-js');
const { sql } = require('drizzle-orm');
const postgres = require('postgres');
const bcrypt = require('bcryptjs');

// Koneksi ke Database PostgreSQL
// Di eksekusi di environment VPS Alpha (127.0.0.1) atau dengan SSH Tunnel
const connectionString = process.env.DATABASE_URL || 'postgresql://jumpa_admin:JumpaS3cur3%21%40%23@127.0.0.1:5432/jumpadb';
const queryClient = postgres(connectionString, { max: 1 });
const db = drizzle(queryClient);

async function seed() {
  console.log('[PKX] Memulai proses injeksi user sesuai PANCA KONSTITUSI X...');

  // Hash password standar untuk injeksi awal
  const defaultPassword = 'password123';
  const salt = bcrypt.genSaltSync(10);
  const passwordHash = bcrypt.hashSync(defaultPassword, salt);

  const tenantTsmId = '1aba6195-f726-4f27-8c20-e309bdf1e754';
  const tenantVpiId = '374c5b80-82a6-46e9-91ef-df29e4c3ef26';

  const users = [
    // Tenant: TSM.ID (2 User)
    { id: '10000000-0000-0000-0000-000000000001', tenantId: tenantTsmId, email: 'tsm@pc24.id', role: 'tenant_admin' },
    { id: '10000000-0000-0000-0000-000000000002', tenantId: tenantTsmId, email: 'idm@idm.me', role: 'user' },

    // Tenant: VPI TSM (4 User)
    { id: '20000000-0000-0000-0000-000000000001', tenantId: tenantVpiId, email: 'sofi@pc24.id', role: 'tenant_admin' },
    { id: '20000000-0000-0000-0000-000000000002', tenantId: tenantVpiId, email: 'keanu@pc24.id', role: 'user' },
    { id: '20000000-0000-0000-0000-000000000003', tenantId: tenantVpiId, email: 'dede@pc24.id', role: 'user' },
    { id: '20000000-0000-0000-0000-000000000004', tenantId: tenantVpiId, email: 'aya@pc24.id', role: 'user' }
  ];

  let successCount = 0;

  for (const u of users) {
    try {
      await db.execute(sql`
        INSERT INTO users (id, tenant_id, email, password_hash, role)
        VALUES (${u.id}, ${u.tenantId}, ${u.email}, ${passwordHash}, ${u.role})
        ON CONFLICT (email) DO UPDATE SET 
          tenant_id = ${u.tenantId}, 
          role = ${u.role}, 
          password_hash = ${passwordHash}
      `);
      console.log(`[OK] User ${u.email} (${u.role}) berhasil diinjeksi ke Tenant ${u.tenantId}.`);
      successCount++;
    } catch (err) {
      console.error(`[ERROR] Gagal injeksi user ${u.email}:`, err.message);
    }
  }

  console.log(`\n[PKX] Proses Selesai. Total sukses: ${successCount}/${users.length}`);
  console.log(`[INFO] Semua user menggunakan password default: '${defaultPassword}'`);
  
  await queryClient.end();
  process.exit(0);
}

seed().catch((err) => {
  console.error('[FATAL] Kesalahan sistem saat seeding:', err);
  process.exit(1);
});
