import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
import dotenv from 'dotenv';

dotenv.config();
const prisma = new PrismaClient();

function slugify(input) {
  return String(input)
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, '')
    .replace(/\s+/g, '-')
    .replace(/-+/g, '-');
}

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

  // --- Super Admin (exactly one) ---
  // The super admin can manage everything, including Users and Finance.
  const superAdminEmail = (process.env.ADMIN_EMAIL || '' ).toLowerCase();
  const superAdminPass = process.env.ADMIN_PASSWORD || '';
  const passwordHash = await bcrypt.hash(superAdminPass, 12);
  
  // Ensure no other account is left as SUPER_ADMIN (enforce a single super admin).
  await prisma.user.updateMany({
    where: { role: 'SUPER_ADMIN', email: { not: superAdminEmail } },
    data: { role: 'ADMIN' },
  });

  await prisma.user.upsert({
    where: { email: superAdminEmail },
    update: { role: 'SUPER_ADMIN' },
    create: {
      email: superAdminEmail,
      name: process.env.ADMIN_NAME || 'CertsNexus Super Admin',
      passwordHash,
      role: 'SUPER_ADMIN',
      emailVerified: true,
    },
  });
  console.log(`Super admin ready: ${superAdminEmail} / ${superAdminPass}`);

  // --- A regular admin (manages everything except Users & Finance) ---
  await prisma.user.upsert({
    where: { email: 'manager@certsnexus.com' },
    update: { role: 'ADMIN' },
    create: {
      email: 'manager@certsnexus.com',
      name: 'CertsNexus Manager',
      passwordHash: await bcrypt.hash('Manager@12345', 12),
      role: 'ADMIN',
      emailVerified: true,
    },
  });
  console.log('Admin ready: manager@certsnexus.com / Manager@12345');

  // --- A demo user ---
  await prisma.user.upsert({
    where: { email: 'user@certsnexus.com' },
    update: {},
    create: {
      email: 'user@certsnexus.com',
      name: 'Demo User',
      passwordHash: await bcrypt.hash('User@12345', 12),
      role: 'USER',
      emailVerified: true,
    },
  });
  console.log('Demo user ready: user@certsnexus.com / User@12345');

  // --- Vendors ---
  const vendorsData = [
    { name: 'Cisco', description: 'Networking certifications (CCNA, CCNP, etc.)' },
    { name: 'Amazon Web Services', description: 'AWS cloud certifications' },
    { name: 'VMware', description: 'Virtualization and cloud certifications' },
  ];

  const vendors = {};
  for (const v of vendorsData) {
    const vendor = await prisma.vendor.upsert({
      where: { slug: slugify(v.name) },
      update: { description: v.description },
      create: { name: v.name, slug: slugify(v.name), description: v.description },
    });
    vendors[v.name] = vendor;
  }

  // --- Sample course (free) for Cisco with questions ---
  const ciscoSlug = slugify('Cisco-CCNA 200-301');
  const ccna = await prisma.course.upsert({
    where: { slug: ciscoSlug },
    update: {},
    create: {
      vendorId: vendors['Cisco'].id,
      title: 'CCNA 200-301',
      slug: ciscoSlug,
      code: '200-301',
      description: 'Cisco Certified Network Associate — fundamentals of networking.',
      priceCents: 1999,
      currency: 'usd',
      isFree: false,
      freeQuestionLimit: 5,
    },
  });

  // --- A free AWS course ---
  const awsSlug = slugify('Amazon Web Services-AWS Cloud Practitioner');
  const awsCourse = await prisma.course.upsert({
    where: { slug: awsSlug },
    update: {},
    create: {
      vendorId: vendors['Amazon Web Services'].id,
      title: 'AWS Cloud Practitioner',
      slug: awsSlug,
      code: 'CLF-C02',
      description: 'Foundational AWS cloud knowledge. Free practice exam.',
      priceCents: 0,
      isFree: true,
      freeQuestionLimit: 5,
    },
  });

  // Seed a question bank (PRACTICE or EXAM) only if that course+category has none yet.
  async function seedBank(courseId, category, list, label) {
    const count = await prisma.question.count({ where: { courseId, category } });
    if (count > 0) return;
    for (let i = 0; i < list.length; i++) {
      const q = list[i];
      await prisma.question.create({
        data: {
          courseId,
          text: q.text,
          explanation: q.explanation,
          type: q.type || 'SINGLE',
          category,
          status: 'APPROVED',
          order: i,
          options: { create: q.options.map((o, idx) => ({ ...o, order: idx })) },
        },
      });
    }
    console.log(`Seeded ${list.length} ${category} questions for ${label}`);
  }

  {
    const ccnaPractice = [
      {
        text: 'Which layer of the OSI model is responsible for logical addressing and routing?',
        type: 'SINGLE',
        explanation: 'The Network layer (Layer 3) handles logical addressing (IP) and routing between networks.',
        options: [
          { text: 'Data Link layer', isCorrect: false },
          { text: 'Network layer', isCorrect: true },
          { text: 'Transport layer', isCorrect: false },
          { text: 'Session layer', isCorrect: false },
        ],
      },
      {
        text: 'What is the default administrative distance of OSPF on a Cisco router?',
        type: 'SINGLE',
        explanation: 'OSPF has a default administrative distance of 110.',
        options: [
          { text: '90', isCorrect: false },
          { text: '100', isCorrect: false },
          { text: '110', isCorrect: true },
          { text: '120', isCorrect: false },
        ],
      },
      {
        text: 'Which two protocols operate at the Transport layer? (Choose two.)',
        type: 'MULTIPLE',
        explanation: 'TCP and UDP are the two Transport-layer protocols.',
        options: [
          { text: 'TCP', isCorrect: true },
          { text: 'IP', isCorrect: false },
          { text: 'UDP', isCorrect: true },
          { text: 'ARP', isCorrect: false },
        ],
      },
      {
        text: 'How many usable host addresses are in a /29 subnet?',
        type: 'SINGLE',
        explanation: 'A /29 has 8 addresses total, minus network and broadcast = 6 usable hosts.',
        options: [
          { text: '4', isCorrect: false },
          { text: '6', isCorrect: true },
          { text: '8', isCorrect: false },
          { text: '14', isCorrect: false },
        ],
      },
    ];

    const ccnaExam = [
      {
        text: 'Which command displays the routing table on a Cisco IOS router?',
        type: 'SINGLE',
        explanation: '"show ip route" displays the IPv4 routing table.',
        options: [
          { text: 'show running-config', isCorrect: false },
          { text: 'show ip route', isCorrect: true },
          { text: 'show interfaces', isCorrect: false },
          { text: 'show version', isCorrect: false },
        ],
      },
      {
        text: 'What protocol automatically assigns IP addresses to hosts?',
        type: 'SINGLE',
        explanation: 'DHCP (Dynamic Host Configuration Protocol) assigns IP addresses automatically.',
        options: [
          { text: 'DNS', isCorrect: false },
          { text: 'DHCP', isCorrect: true },
          { text: 'NAT', isCorrect: false },
          { text: 'SNMP', isCorrect: false },
        ],
      },
      {
        text: 'Which VLAN is the default VLAN on a Cisco switch?',
        type: 'SINGLE',
        explanation: 'VLAN 1 is the default VLAN on Cisco switches.',
        options: [
          { text: 'VLAN 0', isCorrect: false },
          { text: 'VLAN 1', isCorrect: true },
          { text: 'VLAN 10', isCorrect: false },
          { text: 'VLAN 99', isCorrect: false },
        ],
      },
    ];

    await seedBank(ccna.id, 'PRACTICE', ccnaPractice, 'CCNA 200-301');
    await seedBank(ccna.id, 'EXAM', ccnaExam, 'CCNA 200-301');
  }

  // AWS Cloud Practitioner — separate practice and exam banks
  {
    const awsPractice = [
      {
        text: 'Which AWS service provides object storage?',
        explanation: 'Amazon S3 (Simple Storage Service) provides scalable object storage.',
        options: [
          { text: 'Amazon EC2', isCorrect: false },
          { text: 'Amazon S3', isCorrect: true },
          { text: 'Amazon RDS', isCorrect: false },
          { text: 'Amazon VPC', isCorrect: false },
        ],
      },
      {
        text: 'Which pricing model lets you pay only for compute time with no long-term commitment?',
        explanation: 'On-Demand pricing charges per second/hour with no commitment.',
        options: [
          { text: 'Reserved Instances', isCorrect: false },
          { text: 'On-Demand', isCorrect: true },
          { text: 'Savings Plans', isCorrect: false },
          { text: 'Spot Block', isCorrect: false },
        ],
      },
    ];

    const awsExam = [
      {
        text: 'Which AWS service is a managed relational database?',
        explanation: 'Amazon RDS is a managed relational database service.',
        options: [
          { text: 'Amazon RDS', isCorrect: true },
          { text: 'Amazon S3', isCorrect: false },
          { text: 'Amazon Route 53', isCorrect: false },
          { text: 'Amazon CloudFront', isCorrect: false },
        ],
      },
      {
        text: 'Which pillar of the AWS Well-Architected Framework focuses on running and monitoring systems?',
        explanation: 'Operational Excellence focuses on running and monitoring systems to deliver business value.',
        options: [
          { text: 'Operational Excellence', isCorrect: true },
          { text: 'Cost Optimization', isCorrect: false },
          { text: 'Performance Efficiency', isCorrect: false },
          { text: 'Sustainability', isCorrect: false },
        ],
      },
    ];

    await seedBank(awsCourse.id, 'PRACTICE', awsPractice, 'AWS Cloud Practitioner');
    await seedBank(awsCourse.id, 'EXAM', awsExam, 'AWS Cloud Practitioner');
  }

  console.log('Seeding complete.');
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
