import { PrismaClient } from '@prisma/client';
import * as bcrypt from 'bcrypt';

/**
 * Seed-Script: Erstellt den initialen Platform-Admin User.
 *
 * Ausfuehrung:
 *   npx ts-node prisma/seed.ts
 *
 * WICHTIG: Passwort nach erstem Login aendern!
 */

const prisma = new PrismaClient({
  datasources: {
    db: {
      url: process.env.DATABASE_URL_DIRECT || process.env.DATABASE_URL,
    },
  },
});

async function main(): Promise<void> {
  const email = 'admin@xinion.de';

  // Pruefen ob Admin bereits existiert
  const existing = await prisma.user.findUnique({ where: { email } });
  if (existing) {
    console.log(`Admin-User ${email} existiert bereits. Seed uebersprungen.`);
    return;
  }

  // Passwort hashen (Bcrypt Cost 12 gemaess Sicherheitsregel)
  const passwordHash = await bcrypt.hash('ChangeMe123!', 12);

  // Admin-User anlegen
  const user = await prisma.user.create({
    data: {
      email,
      firstName: 'Platform',
      lastName: 'Admin',
      role: 'PLATFORM_ADMIN',
      isActive: true,
      authProvider: {
        create: {
          provider: 'LOCAL',
          passwordHash,
        },
      },
    },
  });

  console.log(`Platform-Admin erstellt: ${user.email} (ID: ${user.id})`);
  console.log('');
  console.log('Zugangsdaten:');
  console.log(`  E-Mail:   ${email}`);
  console.log('  Passwort: ChangeMe123!');
  console.log('');
  console.log('WICHTIG: Passwort nach erstem Login aendern!');
}

main()
  .catch((e: Error) => {
    console.error('Seed fehlgeschlagen:', e.message);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
