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

const prisma = new PrismaClient();

async function main() {
  console.log('🌱 Starting database seed...');

  // 1. Create Superadmin User
  const superadminEmail = process.env.SUPERADMIN_EMAIL || 'admin@iddaai.com';
  const superadminPassword = process.env.SUPERADMIN_PASSWORD || 'Admin123!';

  const existingAdmin = await prisma.user.findUnique({
    where: { email: superadminEmail },
  });

  if (!existingAdmin) {
    const hashedPassword = await bcrypt.hash(superadminPassword, 12);
    
    const admin = await prisma.user.create({
      data: {
        email: superadminEmail,
        passwordHash: hashedPassword,
        firstName: 'Super',
        lastName: 'Admin',
        role: UserRole.superadmin,
        subscriptionStatus: SubscriptionStatus.free,
        isActive: true,
      },
    });

    // Create usage limit for admin
    await prisma.usageLimit.create({
      data: {
        userId: admin.id,
        analysisCount: 0,
        couponCount: 0,
        lastResetDate: new Date(),
      },
    });

    console.log(`✅ Superadmin created: ${superadminEmail}`);
  } else {
    console.log(`ℹ️ Superadmin already exists: ${superadminEmail}`);
  }

  // 2. Create App Settings
  const defaultSettings = [
    { key: 'ai_engine_version', value: 'v8.0' },
    { key: 'daily_analysis_limit_free', value: '3' },
    { key: 'daily_coupon_limit_free', value: '1' },
    { key: 'daily_analysis_limit_premium', value: '50' },
    { key: 'daily_coupon_limit_premium', value: '10' },
    { key: 'maintenance_mode', value: 'false' },
  ];

  for (const setting of defaultSettings) {
    await prisma.appSetting.upsert({
      where: { key: setting.key },
      update: { value: setting.value },
      create: setting,
    });
  }

  console.log('✅ App settings configured');

  // 3. Create sample translations (optional)
  const translations = [
    { key: 'welcome', locale: 'tr', value: 'Hoş geldiniz', namespace: 'common' },
    { key: 'welcome', locale: 'en', value: 'Welcome', namespace: 'common' },
    { key: 'login_success', locale: 'tr', value: 'Giriş başarılı', namespace: 'auth' },
    { key: 'login_success', locale: 'en', value: 'Login successful', namespace: 'auth' },
    { key: 'prediction_generated', locale: 'tr', value: 'Tahmin oluşturuldu', namespace: 'prediction' },
    { key: 'prediction_generated', locale: 'en', value: 'Prediction generated', namespace: 'prediction' },
  ];

  for (const t of translations) {
    await prisma.translation.upsert({
      where: {
        key_locale_namespace: {
          key: t.key,
          locale: t.locale,
          namespace: t.namespace,
        },
      },
      update: { value: t.value },
      create: t,
    });
  }

  console.log('✅ Translations seeded');

  console.log('🎉 Database seed completed!');
}

main()
  .then(async () => {
    await prisma.$disconnect();
  })
  .catch(async (e) => {
    console.error('❌ Seed error:', e);
    await prisma.$disconnect();
    process.exit(1);
  });
