import { db } from "../server/db";
import { users, threatEvents, auditLogs, aiThresholds } from "../shared/schema";
import { createHash } from "crypto";
import { sql } from "drizzle-orm";

const GREEN = "\x1b[32m";
const YELLOW = "\x1b[33m";
const NC = "\x1b[0m";

function hashPassword(password: string): string {
  return createHash("sha256").update(password).digest("hex");
}

async function seed() {
  console.log("   Initializing AEGIS CYBER Database...\n");

  // Check if already seeded
  const existingUsers = await db.execute(sql`SELECT COUNT(*) as count FROM users`);
  const userCount = parseInt((existingUsers.rows[0] as any)?.count || "0");
  
  if (userCount > 0) {
    console.log(`   ${YELLOW}Database already seeded (${userCount} users found)${NC}`);
    console.log("   Skipping seed to preserve existing data\n");
    process.exit(0);
  }

  // Seed Demo Users
  console.log("   Creating demo users...");
  const demoUsers = [
    { username: "admin", password: hashPassword("admin123"), role: "admin" as const, fullName: "System Administrator", department: "IT Security", isActive: true },
    { username: "ciso", password: hashPassword("ciso123"), role: "risk_manager" as const, fullName: "Chief Information Security Officer", department: "Risk Management", isActive: true },
    { username: "auditor", password: hashPassword("auditor123"), role: "auditor" as const, fullName: "Compliance Auditor", department: "Internal Audit", isActive: true },
  ];

  for (const user of demoUsers) {
    await db.insert(users).values(user).onConflictDoNothing();
    console.log(`   ${GREEN}+${NC} Created user: ${user.username} (${user.role})`);
  }

  // Seed AI Thresholds
  console.log("\n   Configuring AI detection thresholds...");
  const thresholds = [
    { thresholdName: "anomaly_score_threshold", thresholdValue: "0.75", description: "Minimum anomaly score to trigger alert" },
    { thresholdName: "velocity_breach_limit", thresholdValue: "10", description: "Max transactions per minute before alert" },
    { thresholdName: "geo_anomaly_distance_km", thresholdValue: "500", description: "Distance threshold for geo-anomaly detection" },
    { thresholdName: "after_hours_start", thresholdValue: "22", description: "Start hour for after-hours detection (24h)" },
    { thresholdName: "after_hours_end", thresholdValue: "6", description: "End hour for after-hours detection (24h)" },
    { thresholdName: "bulk_access_threshold", thresholdValue: "50", description: "Number of records accessed before bulk access alert" },
  ];

  for (const threshold of thresholds) {
    await db.insert(aiThresholds).values(threshold).onConflictDoNothing();
    console.log(`   ${GREEN}+${NC} Set: ${threshold.thresholdName} = ${threshold.thresholdValue}`);
  }

  // Seed Threat Events (98% normal, 2% anomalies)
  console.log("\n   Generating synthetic threat history...");
  
  const branches = ["Kampala HQ", "Entebbe Branch", "Jinja Branch", "Mbarara Branch", "Gulu Branch"];
  const threatTypes: ("INTERNAL_XFER" | "MAKER_ONLY" | "BULK_ACCESS" | "AFTER_HOURS" | "GEO_ANOMALY" | "VELOCITY_BREACH")[] = 
    ["INTERNAL_XFER", "MAKER_ONLY", "BULK_ACCESS", "AFTER_HOURS", "GEO_ANOMALY", "VELOCITY_BREACH"];
  const riskLevels: ("LOW" | "MEDIUM" | "HIGH" | "CRITICAL")[] = ["LOW", "MEDIUM", "HIGH", "CRITICAL"];
  
  const normalEmployees = [
    "EMP-001 (Nakato Sarah)",
    "EMP-002 (Okello James)",
    "EMP-003 (Namukasa Grace)",
    "EMP-004 (Mugisha Peter)",
    "EMP-005 (Apio Mary)",
  ];
  
  const suspiciousEmployees = [
    "EMP-099 (Unknown Access)",
    "EMP-888 (Terminated User)",
    "ADMIN-X (Privilege Escalation)",
  ];

  let normalCount = 0;
  let anomalyCount = 0;
  const totalEvents = 100;

  for (let i = 0; i < totalEvents; i++) {
    const isAnomaly = Math.random() < 0.02; // 2% anomalies
    const daysAgo = Math.floor(Math.random() * 30);
    const timestamp = new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000);

    if (isAnomaly) {
      // High-risk anomaly
      await db.insert(threatEvents).values({
        makerId: suspiciousEmployees[Math.floor(Math.random() * suspiciousEmployees.length)],
        checkerId: null,
        amount: String(Math.floor(Math.random() * 500000000) + 100000000), // Large amounts: 100M-600M UGX
        currency: "UGX",
        threatType: threatTypes[Math.floor(Math.random() * threatTypes.length)],
        riskLevel: Math.random() < 0.5 ? "CRITICAL" : "HIGH",
        terminalIp: `41.210.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}`, // Ugandan IP range
        branch: branches[Math.floor(Math.random() * branches.length)],
        anomalyScore: String((Math.random() * 0.3 + 0.7).toFixed(2)), // 0.70-1.00
        description: "Suspicious high-value transfer detected",
        timestamp,
      });
      anomalyCount++;
    } else {
      // Normal transaction
      await db.insert(threatEvents).values({
        makerId: normalEmployees[Math.floor(Math.random() * normalEmployees.length)],
        checkerId: normalEmployees[Math.floor(Math.random() * normalEmployees.length)],
        amount: String(Math.floor(Math.random() * 5000000) + 100000), // Normal: 100K-5M UGX
        currency: "UGX",
        threatType: threatTypes[Math.floor(Math.random() * threatTypes.length)],
        riskLevel: Math.random() < 0.7 ? "LOW" : "MEDIUM",
        terminalIp: `192.168.${Math.floor(Math.random() * 5)}.${Math.floor(Math.random() * 255)}`, // Internal IPs
        branch: branches[Math.floor(Math.random() * branches.length)],
        anomalyScore: String((Math.random() * 0.4 + 0.1).toFixed(2)), // 0.10-0.50
        isNeutralized: Math.random() < 0.8,
        description: "Standard transaction monitoring",
        timestamp,
      });
      normalCount++;
    }
  }

  console.log(`   ${GREEN}+${NC} Generated ${normalCount} normal events`);
  console.log(`   ${GREEN}+${NC} Generated ${anomalyCount} anomaly events`);

  // Seed Audit Logs
  console.log("\n   Creating audit trail...");
  const auditActions = [
    { action: "LOGIN", resource: "Authentication System", details: "Successful login" },
    { action: "THREAT_VIEWED", resource: "Threat Dashboard", details: "Viewed active threats" },
    { action: "SETTINGS_ACCESSED", resource: "AI Thresholds", details: "Viewed configuration" },
    { action: "REPORT_GENERATED", resource: "PDPO Compliance", details: "Generated Form 7 report" },
  ];

  for (let i = 0; i < 20; i++) {
    const action = auditActions[Math.floor(Math.random() * auditActions.length)];
    const daysAgo = Math.floor(Math.random() * 7);
    await db.insert(auditLogs).values({
      ...action,
      ipAddress: `192.168.1.${Math.floor(Math.random() * 255)}`,
      timestamp: new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000),
    });
  }
  console.log(`   ${GREEN}+${NC} Created 20 audit log entries`);

  console.log(`\n   ${GREEN}Database seeding complete!${NC}\n`);
  process.exit(0);
}

seed().catch((err) => {
  console.error("Seed error:", err);
  process.exit(1);
});
