import dotenv from 'dotenv';
dotenv.config();
import prisma from './src/utils/db';
import bcrypt from 'bcrypt';

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

  // 1. Seed Active Legal Documents
  let ndaDoc = await prisma.legalDocument.findFirst({
    where: { type: 'NDA', version: '1.0' }
  });
  if (!ndaDoc) {
    ndaDoc = await prisma.legalDocument.create({
      data: {
        type: 'NDA',
        version: '1.0',
        content: 'This is the standard Non-Disclosure Agreement content. By signing this document, you agree to keep all technical and business materials confidential.',
        isActive: true,
      }
    });
    console.log('Seeded NDA Document.');
  } else {
    console.log('NDA Document already exists.');
  }

  let msaDoc = await prisma.legalDocument.findFirst({
    where: { type: 'MSA', version: '1.0' }
  });
  if (!msaDoc) {
    msaDoc = await prisma.legalDocument.create({
      data: {
        type: 'MSA',
        version: '1.0',
        content: 'This is the standard Master Services Agreement content. It defines the core relationship, deliverables, and service levels between Tech4Biz and the partner.',
        isActive: true,
      }
    });
    console.log('Seeded MSA Document.');
  } else {
    console.log('MSA Document already exists.');
  }

  // 2. Hash Password
  const passwordHash = await bcrypt.hash('Password123', 10);

  // Create default Partner organization
  let partnerOrg = await prisma.organization.findFirst({
    where: { name: 'PARTNER' }
  });
  if (!partnerOrg) {
    partnerOrg = await prisma.organization.create({
      data: { name: 'PARTNER' }
    });
    console.log('Seeded PARTNER organization.');
  }

  // 3. Seed Admin
  const adminEmail = 'admin@tech4biz.com';
  let adminUser = await prisma.user.findUnique({ where: { email: adminEmail } });
  if (!adminUser) {
    adminUser = await prisma.user.create({
      data: {
        email: adminEmail,
        passwordHash,
        role: 'ADMIN',
        onboardingStatus: 'APPROVED',
        mfaEnabled: false,
      }
    });
    console.log(`Seeded Admin User: ${adminEmail}`);
  } else {
    console.log(`Admin User already exists: ${adminEmail}`);
  }

  // 4. Seed Partner: Fully active & approved
  const activeEmail = 'active-partner@partner.com';
  let activeUser = await prisma.user.findUnique({ where: { email: activeEmail } });
  if (!activeUser) {
    activeUser = await prisma.user.create({
      data: {
        email: activeEmail,
        passwordHash,
        role: 'PARTNER_USER',
        onboardingStatus: 'APPROVED',
        mfaEnabled: false,
        organizationId: partnerOrg.id
      }
    });
    console.log(`Seeded Partner (Approved): ${activeEmail}`);

    // Seed LegalAcceptance for NDA
    await prisma.legalAcceptance.create({
      data: {
        docId: ndaDoc.id,
        userId: activeUser.id,
        ipAddress: '127.0.0.1',
        signatureHash: 'sha256-dummyndaacceptactive987654321',
        acceptedAt: new Date()
      }
    });
    // Seed LegalAcceptance for MSA
    await prisma.legalAcceptance.create({
      data: {
        docId: msaDoc.id,
        userId: activeUser.id,
        ipAddress: '127.0.0.1',
        signatureHash: 'sha256-dummymsaacceptactive987654321',
        acceptedAt: new Date()
      }
    });
    console.log('Seeded Legal Acceptances for NDA/MSA for active partner.');
  } else {
    console.log(`Partner (Approved) already exists: ${activeEmail}`);
  }

  // 5. Seed Ecosystem Offerings
  const offerings = [
    {
      name: 'CodeNuk',
      type: 'PRODUCT',
      tagline: 'Accelerate software delivery with deterministic AI-powered backend generation.',
      description: 'CodeNuk is an enterprise-grade AI platform that transforms Software Requirements Specifications (SRS) into production-ready backend foundations. By deterministically generating architecture, database schemas, APIs, security components, testing frameworks, and deployment-ready assets directly from business requirements, CodeNuk eliminates weeks of repetitive engineering effort while ensuring consistency, traceability, and architectural standardization.',
      benefits: [
        'Accelerates software development and time-to-market.',
        'Standardizes backend architecture across projects.',
        'Minimizes manual engineering effort and setup time.',
        'Improves code consistency and traceability to business requirements.',
        'Delivers deployment-ready backend assets with built-in testing and documentation.',
        'Commercial model based on one-time project pricing instead of recurring subscriptions.'
      ],
      websiteUrl: 'https://codenuk.com',
      ctaText: 'Visit CodeNuk',
      logoIcon: 'Code',
      logoUrl: 'codenuk',
      orderIndex: 0
    },
    {
      name: 'Tech4Biz Solutions',
      type: 'SERVICE',
      tagline: 'A strategic Technology Execution Partner delivering end-to-end digital engineering and transformation services.',
      description: 'Tech4Biz Solutions partners with enterprises to architect, build, integrate, and scale secure, future-ready technology solutions. Our expertise spans software engineering, AI, cloud, automation, IoT, and cybersecurity, enabling organizations to accelerate digital transformation, modernize legacy systems, and deliver technology initiatives with speed, quality, and confidence.',
      benefits: [
        'Custom Software Engineering & Cloud Solutions',
        'AI, Automation & IoT Integration',
        'Legacy Modernization & Cybersecurity Audit',
        'Strategic Technology Execution & Ownership'
      ],
      websiteUrl: 'https://www.tech4bizsolutions.com',
      ctaText: 'Visit Tech4Biz',
      logoIcon: 'Briefcase',
      logoUrl: 'tech4biz',
      orderIndex: 1
    },
    {
      name: 'Audittrax Labs',
      type: 'SERVICE',
      tagline: 'An AI-powered platform delivering Tech Due Diligence, Technical Advisory, and Continuous Assurance.',
      description: 'Audittrax Labs enables enterprises, investors, and business leaders to make informed technology decisions through Tech Due Diligence, Technical Advisory, and AI-driven audit, risk, and compliance services. By combining continuous assurance, automated controls monitoring, and expert technical assessments, the platform helps organizations evaluate technology landscapes, mitigate risk, strengthen governance, and accelerate confident business decisions.',
      benefits: [
        'AI-Driven Compliance & Tech Auditing',
        'Comprehensive Tech Due Diligence for Investors',
        'Automated Security & Risk Monitoring',
        'Technical Advisory & Governance Solutions'
      ],
      websiteUrl: 'https://auditraxlabs.com',
      ctaText: 'Visit Audittrax',
      logoIcon: 'Shield',
      logoUrl: 'auditraxlabs',
      orderIndex: 2
    },
    {
      name: 'Cloudtopiaa',
      type: 'PRODUCT',
      tagline: 'An enterprise cloud platform delivering secure, scalable, and high-performance infrastructure services.',
      description: 'Cloudtopiaa enables organizations to accelerate their cloud journey through enterprise-grade infrastructure, storage, networking, security, and cloud-native services. Designed for modern workloads, the platform helps businesses migrate, deploy, manage, and scale applications with improved resilience, operational efficiency, and cost optimization.',
      benefits: [
        'Enterprise-grade secure infrastructure',
        'High-performance storage, networking, and cloud-native services',
        'Cost optimization & operational efficiency audit',
        'Seamless cloud migration and automation tools'
      ],
      websiteUrl: 'https://cloudtopiaa.com',
      ctaText: 'Visit Cloudtopiaa',
      logoIcon: 'Cloud',
      logoUrl: 'cloudtopiaa',
      orderIndex: 3
    }
  ];

  for (const offering of offerings) {
    await prisma.ecosystemOffering.upsert({
      where: { name: offering.name },
      update: offering,
      create: offering
    });
  }
  console.log('Seeded Ecosystem Offerings.');

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

seed()
  .catch((err) => {
    console.error('Seeding failed:', err);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
