/**
 * Database Seeder
 *
 * Populates initial data:
 * - Admin user for backend panel
 * - System settings for AI translation service
 * - Pricing configuration
 * - PayPal configuration
 * - Test license keys for E2E testing
 */

import crypto from 'crypto';
import { PrismaClient } from '@prisma/client';
import { hashPassword } from '../src/utils/encryption';

const prisma = new PrismaClient();

function hashLicenseKey(key: string): string {
  return crypto.createHash('sha256').update(key).digest('hex');
}

/**
 * Test license keys — use these in E2E tests and manual testing.
 *
 * MULT-TEST-E2E0-PRO1  — multilingual, professional, 25 sites, 5 languages
 * MULT-TEST-E2E0-PER1  — multilingual, starter (personal), 3 sites, 1 language
 * MULT-TEST-E2E0-AGY1  — multilingual, enterprise (agency), unlimited
 * TRAN-TEST-E2E0-PRO1  — translate, professional, 25 sites
 * TRAN-TEST-E2E0-PER1  — translate, starter (personal), 3 sites
 * TRAN-TEST-E2E0-AGY1  — translate, enterprise (agency), unlimited
 * MULT-TEST-E2E0-EXP1  — multilingual, expired (for testing expiration)
 * TRAN-TEST-E2E0-EXP1  — translate, expired (for testing expiration)
 */
const TEST_LICENSES = [
  {
    key: 'MULT-TEST-E2E0-PRO1',
    plugin: 'multilingual',
    plan_tier: 'professional' as const,
    sites_allowed: 25,
    languages_allowed: 5,
    expires_at: new Date('2028-01-01T00:00:00Z'),
    status: 'active' as const,
  },
  {
    key: 'MULT-TEST-E2E0-PER1',
    plugin: 'multilingual',
    plan_tier: 'starter' as const,
    sites_allowed: 3,
    languages_allowed: 1,
    expires_at: new Date('2028-01-01T00:00:00Z'),
    status: 'active' as const,
  },
  {
    key: 'MULT-TEST-E2E0-AGY1',
    plugin: 'multilingual',
    plan_tier: 'enterprise' as const,
    sites_allowed: -1,
    languages_allowed: -1,
    expires_at: new Date('2028-01-01T00:00:00Z'),
    status: 'active' as const,
  },
  {
    key: 'TRAN-TEST-E2E0-PRO1',
    plugin: 'translate',
    plan_tier: 'professional' as const,
    sites_allowed: 25,
    languages_allowed: 5,
    expires_at: new Date('2028-01-01T00:00:00Z'),
    status: 'active' as const,
  },
  {
    key: 'TRAN-TEST-E2E0-PER1',
    plugin: 'translate',
    plan_tier: 'starter' as const,
    sites_allowed: 3,
    languages_allowed: 1,
    expires_at: new Date('2028-01-01T00:00:00Z'),
    status: 'active' as const,
  },
  {
    key: 'TRAN-TEST-E2E0-AGY1',
    plugin: 'translate',
    plan_tier: 'enterprise' as const,
    sites_allowed: -1,
    languages_allowed: -1,
    expires_at: new Date('2028-01-01T00:00:00Z'),
    status: 'active' as const,
  },
  {
    key: 'MULT-TEST-E2E0-EXP1',
    plugin: 'multilingual',
    plan_tier: 'professional' as const,
    sites_allowed: 25,
    languages_allowed: 5,
    expires_at: new Date('2024-01-01T00:00:00Z'),
    status: 'active' as const,
  },
  {
    key: 'TRAN-TEST-E2E0-EXP1',
    plugin: 'translate',
    plan_tier: 'professional' as const,
    sites_allowed: 25,
    languages_allowed: 5,
    expires_at: new Date('2024-01-01T00:00:00Z'),
    status: 'active' as const,
  },
];

async function main() {
  console.log('Seeding database...');

  // 1. Create admin user
  const adminPassword = await hashPassword('admin123');
  const admin = await prisma.adminUser.upsert({
    where: { email: 'admin@translate.press.zone' },
    update: {},
    create: {
      email: 'admin@translate.press.zone',
      password_hash: adminPassword,
      role: 'admin',
      is_active: true,
    },
  });
  console.log('Admin user created:', admin.email);

  // 2. System settings - AI translation service configuration
  const settings = [
    {
      key: 'gemini_api_key',
      value: JSON.stringify('your-gemini-api-key-here'),
      description: 'AI translation API key',
    },
    {
      key: 'pricing_per_1k_characters',
      value: JSON.stringify(0.002),
      description: 'Cost per 1K characters for translation (USD)',
    },
    {
      key: 'paypal_mode',
      value: JSON.stringify('sandbox'),
      description: 'PayPal mode (sandbox or live)',
    },
  ];

  for (const setting of settings) {
    await prisma.systemSetting.upsert({
      where: { key: setting.key },
      update: { value: setting.value },
      create: setting,
    });
    console.log('Setting created:', setting.key);
  }

  // 3. Subscription tiers
  const translateTiers = [
    {
      slug: 'starter',
      name: 'Starter',
      description: 'For individuals and small projects',
      monthly_price: 29,
      annual_price: 290,
      credit_allocation: 1000000,
      rate_limit: 60,
      plugin: 'translate',
      plugin_limits: {},
      features: ['1M characters/month', '60 req/min', 'Email support'],
      display_order: 0,
      is_active: true,
    },
    {
      slug: 'professional',
      name: 'Professional',
      description: 'For growing businesses',
      monthly_price: 99,
      annual_price: 990,
      credit_allocation: 4000000,
      rate_limit: 120,
      plugin: 'translate',
      plugin_limits: {},
      features: ['4M characters/month', '120 req/min', 'Priority support'],
      display_order: 1,
      is_active: true,
    },
    {
      slug: 'enterprise',
      name: 'Enterprise',
      description: 'For large-scale operations',
      monthly_price: 299,
      annual_price: 2990,
      credit_allocation: 15000000,
      rate_limit: 0,
      plugin: 'translate',
      plugin_limits: {},
      features: ['15M characters/month', 'Unlimited req/min', 'Dedicated support'],
      display_order: 2,
      is_active: true,
    },
  ];

  const multilingualTiers = [
    {
      slug: 'starter',
      name: 'Starter',
      description: 'For personal multilingual sites',
      monthly_price: 9,
      annual_price: 90,
      credit_allocation: 0,
      rate_limit: 0,
      plugin: 'multilingual',
      plugin_limits: { sites_allowed: 3, languages_allowed: 1 },
      features: ['3 sites', '1 language', 'Email support'],
      display_order: 0,
      is_active: true,
    },
    {
      slug: 'professional',
      name: 'Professional',
      description: 'For growing multilingual businesses',
      monthly_price: 29,
      annual_price: 290,
      credit_allocation: 0,
      rate_limit: 0,
      plugin: 'multilingual',
      plugin_limits: { sites_allowed: 25, languages_allowed: 5 },
      features: ['25 sites', '5 languages', 'Priority support'],
      display_order: 1,
      is_active: true,
    },
    {
      slug: 'enterprise',
      name: 'Enterprise',
      description: 'For large-scale multilingual operations',
      monthly_price: 99,
      annual_price: 990,
      credit_allocation: 0,
      rate_limit: 0,
      plugin: 'multilingual',
      plugin_limits: { sites_allowed: -1, languages_allowed: -1 },
      features: ['Unlimited sites', 'Unlimited languages', 'Dedicated support'],
      display_order: 2,
      is_active: true,
    },
  ];

  for (const tier of [...translateTiers, ...multilingualTiers]) {
    await prisma.subscriptionTier.upsert({
      where: { plugin_slug: { plugin: tier.plugin, slug: tier.slug } },
      update: {
        name: tier.name,
        description: tier.description,
        monthly_price: tier.monthly_price,
        annual_price: tier.annual_price,
        credit_allocation: tier.credit_allocation,
        rate_limit: tier.rate_limit,
        plugin_limits: tier.plugin_limits,
        features: tier.features,
        display_order: tier.display_order,
        is_active: tier.is_active,
      },
      create: tier,
    });
    console.log(`Tier seeded: ${tier.plugin}/${tier.slug}`);
  }

  // 4. Test license keys (renumbered from original 3)
  for (const lic of TEST_LICENSES) {
    const key_hash = hashLicenseKey(lic.key);
    const key_last4 = lic.key.replace(/-/g, '').slice(-4);

    await prisma.license.upsert({
      where: { key_hash },
      update: {
        plan_tier: lic.plan_tier,
        status: lic.status,
        sites_allowed: lic.sites_allowed,
        languages_allowed: lic.languages_allowed,
        expires_at: lic.expires_at,
      },
      create: {
        key_hash,
        key_last4,
        plugin: lic.plugin,
        plan_tier: lic.plan_tier,
        status: lic.status,
        sites_allowed: lic.sites_allowed,
        languages_allowed: lic.languages_allowed,
        expires_at: lic.expires_at,
      },
    });
    console.log(`License seeded: ${lic.key} (${lic.plugin}/${lic.plan_tier})`);
  }

  // 5. Clear any stale activations for test licenses so tests start clean
  for (const lic of TEST_LICENSES) {
    const key_hash = hashLicenseKey(lic.key);
    const license = await prisma.license.findUnique({ where: { key_hash } });
    if (license) {
      await prisma.licenseActivation.deleteMany({
        where: { license_id: license.id },
      });
    }
  }
  console.log('Cleared stale test license activations');

  console.log('Seeding completed!');
}

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