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

const prisma = new PrismaClient();

async function main() {
  console.log('🌱 Starting database seed...');
  
  // Test connection
  try {
    await prisma.$connect();
    console.log('✅ Database connected successfully');
  } catch (error) {
    console.error('❌ Database connection failed:', error);
    throw error;
  }

  // Check if tables exist by counting users
  try {
    const userCount = await prisma.user.count();
    console.log(`📊 Current user count: ${userCount}`);
  } catch (error) {
    console.error('❌ Error accessing user table:', error);
    throw error;
  }

  // Clear existing data (be careful in production!)
  console.log('🧹 Clearing existing data...');
  
  try {
    await prisma.auditLog.deleteMany();
    await prisma.sLATracking.deleteMany();
    await prisma.contractorPerformance.deleteMany();
    await prisma.exportAttempt.deleteMany();
    await prisma.notification.deleteMany();
    await prisma.contract.deleteMany();
    await prisma.quote.deleteMany();
    await prisma.lead.deleteMany();
    await prisma.partner.deleteMany();
    await prisma.customer.deleteMany();
    await prisma.session.deleteMany();
    await prisma.account.deleteMany();
    await prisma.user.deleteMany();
    await prisma.pricingRate.deleteMany();
    console.log('✅ Data cleared successfully');
  } catch (error) {
    console.error('❌ Error clearing data:', error);
    throw error;
  }

  // Hash password for all users
  const hashedPassword = await bcrypt.hash('johndoe123', 12);
  const adminPassword = await bcrypt.hash('admin123', 12);

  // Create test users with different roles
  console.log('👤 Creating users...');
  
  // Admin user
  const adminUser = await prisma.user.create({
    data: {
      email: 'admin@quote2contract.com',
      password: adminPassword,
      firstName: 'System',
      lastName: 'Admin',
      name: 'System Admin',
      role: 'ADMIN',
      companyName: 'Quote2Contract',
      phone: '+1-555-0100',
      address: '123 Business Ave',
      city: 'Austin',
      state: 'TX',
      country: 'USA',
      zipCode: '78701',
      trustScore: 100.0,
      isActive: true,
    }
  });

  // Default test user (required for testing)
  const testUser = await prisma.user.create({
    data: {
      email: 'john@doe.com',
      password: hashedPassword,
      firstName: 'John',
      lastName: 'Doe',
      name: 'John Doe',
      role: 'ADMIN',
      companyName: 'Test Company',
      phone: '+1-555-0101',
      address: '456 Test St',
      city: 'Austin',
      state: 'TX',
      country: 'USA',
      zipCode: '78702',
      trustScore: 95.0,
      isActive: true,
    }
  });

  // Sales users
  const salesUser1 = await prisma.user.create({
    data: {
      email: 'sarah.johnson@quote2contract.com',
      password: hashedPassword,
      firstName: 'Sarah',
      lastName: 'Johnson',
      name: 'Sarah Johnson',
      role: 'SALES',
      companyName: 'Quote2Contract',
      phone: '+1-555-0102',
      address: '789 Sales Drive',
      city: 'Austin',
      state: 'TX',
      country: 'USA',
      zipCode: '78703',
      trustScore: 88.5,
      isActive: true,
    }
  });

  const salesUser2 = await prisma.user.create({
    data: {
      email: 'mike.chen@quote2contract.com',
      password: hashedPassword,
      firstName: 'Mike',
      lastName: 'Chen',
      name: 'Mike Chen',
      role: 'SALES',
      companyName: 'Quote2Contract',
      phone: '+1-555-0103',
      address: '321 Revenue Road',
      city: 'Austin',
      state: 'TX',
      country: 'USA',
      zipCode: '78704',
      trustScore: 92.3,
      isActive: true,
    }
  });

  // Contractor users
  const contractor1 = await prisma.user.create({
    data: {
      email: 'david.roofing@contractornetwork.com',
      password: hashedPassword,
      firstName: 'David',
      lastName: 'Martinez',
      name: 'David Martinez',
      role: 'CONTRACTOR',
      companyName: 'Elite Roofing Solutions',
      phone: '+1-555-0104',
      address: '555 Contractor Way',
      city: 'Dallas',
      state: 'TX',
      country: 'USA',
      zipCode: '75201',
      trustScore: 96.7,
      isActive: true,
    }
  });

  const contractor2 = await prisma.user.create({
    data: {
      email: 'lisa.pools@contractornetwork.com',
      password: hashedPassword,
      firstName: 'Lisa',
      lastName: 'Thompson',
      name: 'Lisa Thompson',
      role: 'CONTRACTOR',
      companyName: 'Crystal Clear Pools',
      phone: '+1-555-0105',
      address: '777 Pool Plaza',
      city: 'Houston',
      state: 'TX',
      country: 'USA',
      zipCode: '77001',
      trustScore: 94.2,
      isActive: true,
    }
  });

  // Customer users
  const customer1 = await prisma.user.create({
    data: {
      email: 'emily.homeowner@gmail.com',
      password: hashedPassword,
      firstName: 'Emily',
      lastName: 'Rodriguez',
      name: 'Emily Rodriguez',
      role: 'CUSTOMER',
      phone: '+1-555-0106',
      address: '123 Maple Street',
      city: 'Austin',
      state: 'TX',
      country: 'USA',
      zipCode: '78705',
      trustScore: 0.0,
      isActive: true,
    }
  });

  const customer2 = await prisma.user.create({
    data: {
      email: 'robert.smith@yahoo.com',
      password: hashedPassword,
      firstName: 'Robert',
      lastName: 'Smith',
      name: 'Robert Smith',
      role: 'CUSTOMER',
      phone: '+1-555-0107',
      address: '456 Oak Drive',
      city: 'Dallas',
      state: 'TX',
      country: 'USA',
      zipCode: '75202',
      trustScore: 0.0,
      isActive: true,
    }
  });

  // Create Partner profiles for contractors
  console.log('🤝 Creating partner profiles...');
  
  const partner1 = await prisma.partner.create({
    data: {
      userId: contractor1.id,
      companyName: 'Elite Roofing Solutions',
      licenseNumber: 'TX-ROOF-2024-001',
      licenseExpiry: new Date('2025-12-31'),
      services: ['Roofing', 'Gutters', 'Roof Repairs'],
      serviceAreas: ['Austin', 'Dallas', 'San Antonio'],
      isVerified: true,
      verificationStatus: 'VERIFIED',
      businessAddress: '555 Contractor Way, Dallas, TX 75201',
      businessPhone: '+1-555-0104',
      website: 'https://eliteroofingsolutions.com',
      description: 'Professional roofing services with 15+ years experience. Specializing in residential and commercial roofing solutions.',
    }
  });

  const partner2 = await prisma.partner.create({
    data: {
      userId: contractor2.id,
      companyName: 'Crystal Clear Pools',
      licenseNumber: 'TX-POOL-2024-002',
      licenseExpiry: new Date('2025-11-30'),
      services: ['Pool Installation', 'Pool Maintenance', 'Pool Repairs'],
      serviceAreas: ['Houston', 'Austin', 'Galveston'],
      isVerified: true,
      verificationStatus: 'VERIFIED',
      businessAddress: '777 Pool Plaza, Houston, TX 77001',
      businessPhone: '+1-555-0105',
      website: 'https://crystalclearpools.com',
      description: 'Expert pool installation and maintenance services. Creating beautiful backyard oases for Texas families.',
    }
  });

  // Create Customer profiles
  console.log('👥 Creating customer profiles...');
  
  await prisma.customer.create({
    data: {
      userId: customer1.id,
      preferredServices: ['Roofing', 'Gutters'],
      propertyType: 'Single Family Home',
      propertySize: '2500-3000 sq ft',
      budget: '$15,000-$25,000',
    }
  });

  await prisma.customer.create({
    data: {
      userId: customer2.id,
      preferredServices: ['Pool Installation'],
      propertyType: 'Single Family Home',
      propertySize: '3000-4000 sq ft',
      budget: '$40,000-$60,000',
    }
  });

  // Create sample leads
  console.log('📋 Creating sample leads...');
  
  const lead1 = await prisma.lead.create({
    data: {
      firstName: 'Jennifer',
      lastName: 'Wilson',
      email: 'jennifer.wilson@gmail.com',
      phone: '+1-555-0201',
      address: '789 Pine Avenue',
      city: 'Austin',
      state: 'TX',
      zipCode: '78706',
      source: 'WEB',
      services: ['Roofing'],
      description: 'Need roof replacement due to hail damage from recent storm.',
      budget: '$20,000-$30,000',
      timeline: 'Within 2 months',
      status: 'NEW',
      score: 85.5,
      priority: 'HIGH',
      assignedToId: salesUser1.id,
      createdById: adminUser.id,
    }
  });

  const lead2 = await prisma.lead.create({
    data: {
      firstName: 'Michael',
      lastName: 'Davis',
      email: 'michael.davis@outlook.com',
      phone: '+1-555-0202',
      address: '321 Cedar Lane',
      city: 'Dallas',
      state: 'TX',
      zipCode: '75203',
      source: 'REFERRAL',
      services: ['Pool Installation'],
      description: 'Looking to install an inground pool for summer 2024.',
      budget: '$50,000-$70,000',
      timeline: 'Spring 2024',
      status: 'QUALIFIED',
      score: 92.3,
      priority: 'HIGH',
      assignedToId: salesUser2.id,
      createdById: adminUser.id,
      partnerId: partner2.id,
    }
  });

  const lead3 = await prisma.lead.create({
    data: {
      firstName: 'Amanda',
      lastName: 'Brown',
      email: 'amanda.brown@yahoo.com',
      phone: '+1-555-0203',
      address: '654 Elm Street',
      city: 'Houston',
      state: 'TX',
      zipCode: '77002',
      source: 'ADVERTISEMENT',
      services: ['Gutters', 'Roofing'],
      description: 'Need gutter replacement and minor roof repairs.',
      budget: '$5,000-$10,000',
      timeline: 'Within 6 weeks',
      status: 'CONTACTED',
      score: 73.8,
      priority: 'MEDIUM',
      assignedToId: salesUser1.id,
      createdById: adminUser.id,
      contactedAt: new Date(),
    }
  });

  // Create sample quotes
  console.log('💰 Creating sample quotes...');
  
  const quote1 = await prisma.quote.create({
    data: {
      quoteNumber: 'Q2C-2024-0001',
      leadId: lead1.id,
      userId: customer1.id,
      partnerId: partner1.id,
      propertyData: {
        address: '789 Pine Avenue, Austin, TX 78706',
        coordinates: { lat: 30.2672, lng: -97.7431 },
        measurements: {
          roofArea: 2850,
          roofPerimeter: 240,
          roofPitch: '6/12',
          roofType: 'Gable'
        }
      },
      services: ['Roof Replacement', 'Gutters'],
      lineItems: [
        {
          description: 'Architectural Shingle Roof Replacement',
          quantity: 2850,
          unit: 'sq ft',
          unitPrice: 8.50,
          total: 24225.00
        },
        {
          description: 'Seamless Aluminum Gutters',
          quantity: 240,
          unit: 'linear ft',
          unitPrice: 12.00,
          total: 2880.00
        },
        {
          description: 'Labor and Installation',
          quantity: 1,
          unit: 'job',
          unitPrice: 3500.00,
          total: 3500.00
        }
      ],
      subtotal: 30605.00,
      discounts: 1500.00,
      taxes: 2324.41,
      total: 31429.41,
      validUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days from now
      status: 'SENT',
      notes: 'Price includes removal of old roofing material and disposal.',
      termsConditions: 'Payment terms: 10% down, 40% at material delivery, 50% upon completion.',
      sentAt: new Date(),
    }
  });

  const quote2 = await prisma.quote.create({
    data: {
      quoteNumber: 'Q2C-2024-0002',
      leadId: lead2.id,
      userId: customer2.id,
      partnerId: partner2.id,
      propertyData: {
        address: '321 Cedar Lane, Dallas, TX 75203',
        coordinates: { lat: 32.7767, lng: -96.7970 },
        measurements: {
          poolLength: 40,
          poolWidth: 20,
          poolDepth: 8,
          poolArea: 800,
          deckArea: 400
        }
      },
      services: ['Inground Pool Installation'],
      lineItems: [
        {
          description: 'Gunite Pool Shell (40x20x8)',
          quantity: 1,
          unit: 'pool',
          unitPrice: 35000.00,
          total: 35000.00
        },
        {
          description: 'Pool Equipment Package',
          quantity: 1,
          unit: 'package',
          unitPrice: 8500.00,
          total: 8500.00
        },
        {
          description: 'Concrete Deck (400 sq ft)',
          quantity: 400,
          unit: 'sq ft',
          unitPrice: 15.00,
          total: 6000.00
        },
        {
          description: 'Pool Finish - Plaster',
          quantity: 1,
          unit: 'pool',
          unitPrice: 4500.00,
          total: 4500.00
        }
      ],
      subtotal: 54000.00,
      discounts: 2000.00,
      taxes: 4160.00,
      total: 56160.00,
      validUntil: new Date(Date.now() + 45 * 24 * 60 * 60 * 1000), // 45 days from now
      status: 'ACCEPTED',
      isAccepted: true,
      acceptedAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000), // 5 days ago
      notes: 'Includes all permits and inspections. Pool completion estimated 8-10 weeks.',
      termsConditions: 'Payment schedule: 15% deposit, 25% at excavation, 25% at shell completion, 25% at equipment installation, 10% final payment.',
      sentAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7 days ago
    }
  });

  const quote3 = await prisma.quote.create({
    data: {
      quoteNumber: 'Q2C-2024-0003',
      leadId: lead3.id,
      userId: customer1.id,
      partnerId: partner1.id,
      propertyData: {
        address: '654 Elm Street, Houston, TX 77002',
        coordinates: { lat: 29.7604, lng: -95.3698 },
        measurements: {
          gutterLength: 180,
          roofArea: 1200,
          roofPitch: '4/12',
        }
      },
      services: ['Gutter Replacement', 'Minor Roof Repairs'],
      lineItems: [
        {
          description: 'Seamless Aluminum Gutters',
          quantity: 180,
          unit: 'linear ft',
          unitPrice: 12.00,
          total: 2160.00
        },
        {
          description: 'Gutter Guards',
          quantity: 180,
          unit: 'linear ft',
          unitPrice: 8.00,
          total: 1440.00
        },
        {
          description: 'Roof Repairs - Shingle Replacement',
          quantity: 50,
          unit: 'sq ft',
          unitPrice: 15.00,
          total: 750.00
        },
        {
          description: 'Labor and Installation',
          quantity: 1,
          unit: 'job',
          unitPrice: 1200.00,
          total: 1200.00
        }
      ],
      subtotal: 5550.00,
      discounts: 250.00,
      taxes: 423.98,
      total: 5723.98,
      validUntil: new Date(Date.now() + 20 * 24 * 60 * 60 * 1000), // 20 days from now
      status: 'SENT',
      notes: 'Price includes removal of old gutters and disposal. Roof repairs cover up to 50 sq ft of damaged shingles.',
      termsConditions: 'Payment terms: 50% deposit, 50% upon completion. 1-year warranty on all work.',
      sentAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000), // 2 days ago
    }
  });

  // Create sample contract from accepted quote
  console.log('📄 Creating sample contracts...');
  
  const contract1 = await prisma.contract.create({
    data: {
      contractNumber: 'CNT-2024-0001',
      quoteId: quote2.id,
      userId: customer2.id,
      partnerId: partner2.id,
      templateVersion: '1.0',
      contractData: {
        customerName: 'Michael Davis',
        contractorName: 'Crystal Clear Pools',
        projectDescription: 'Inground Pool Installation',
        workLocation: '321 Cedar Lane, Dallas, TX 75203',
        contractValue: 56160.00,
        paymentSchedule: [
          { milestone: 'Contract Signing', percentage: 15, amount: 8424.00 },
          { milestone: 'Excavation Complete', percentage: 25, amount: 14040.00 },
          { milestone: 'Shell Complete', percentage: 25, amount: 14040.00 },
          { milestone: 'Equipment Installation', percentage: 25, amount: 14040.00 },
          { milestone: 'Project Completion', percentage: 10, amount: 5616.00 }
        ]
      },
      trustScore: 94.2,
      slaTerms: {
        projectDuration: '10 weeks',
        warrantyPeriod: '2 years',
        milestones: [
          {
            name: 'Permits Obtained',
            deadline: '1 week',
            description: 'All required permits and approvals secured'
          },
          {
            name: 'Excavation Complete',
            deadline: '2 weeks',
            description: 'Pool excavation and utility rough-in complete'
          },
          {
            name: 'Shell Installation',
            deadline: '4 weeks',
            description: 'Gunite shell formed and cured'
          },
          {
            name: 'Equipment Installation',
            deadline: '8 weeks',
            description: 'All pool equipment installed and tested'
          },
          {
            name: 'Final Completion',
            deadline: '10 weeks',
            description: 'Pool finished, deck complete, final inspection passed'
          }
        ]
      },
      status: 'ACTIVE',
      signedAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000), // 3 days ago
      customerSignature: 'Michael Davis - Digital Signature',
      contractorSignature: 'Lisa Thompson - Digital Signature',
      startDate: new Date(),
      completionDate: new Date(Date.now() + 70 * 24 * 60 * 60 * 1000), // 10 weeks from now
    }
  });

  // Create SLA tracking for the contract
  console.log('⏰ Creating SLA tracking...');
  
  await prisma.sLATracking.create({
    data: {
      contractId: contract1.id,
      milestone: 'Permits Obtained',
      targetDate: new Date(Date.now() + 4 * 24 * 60 * 60 * 1000), // 4 days from now
      status: 'ON_TRACK',
    }
  });

  await prisma.sLATracking.create({
    data: {
      contractId: contract1.id,
      milestone: 'Excavation Complete',
      targetDate: new Date(Date.now() + 11 * 24 * 60 * 60 * 1000), // 11 days from now
      status: 'ON_TRACK',
    }
  });

  // Create contractor performance records
  console.log('📊 Creating performance metrics...');
  
  // Create monthly performance records for better visualization
  const months = ['2024-04', '2024-05', '2024-06', '2024-07', '2024-08', '2024-09', '2024-10'];
  
  for (const month of months) {
    // Contractor 1 - Elite Roofing Solutions
    const baseRevenue1 = 45000 + Math.random() * 30000;
    const baseContracts1 = 3 + Math.floor(Math.random() * 4);
    
    await prisma.contractorPerformance.create({
      data: {
        userId: contractor1.id,
        partnerId: partner1.id,
        period: month,
        leadsAssigned: Math.floor(3 + Math.random() * 5),
        quotesSubmitted: Math.floor(2 + Math.random() * 4),
        contractsWon: baseContracts1,
        revenue: baseRevenue1,
        averageRating: 4.5 + Math.random() * 0.4,
        completionRate: 90 + Math.random() * 8,
        customerSatisfaction: 4.3 + Math.random() * 0.6,
      }
    });
    
    // Contractor 2 - Crystal Clear Pools
    const baseRevenue2 = 55000 + Math.random() * 40000;
    const baseContracts2 = 2 + Math.floor(Math.random() * 3);
    
    await prisma.contractorPerformance.create({
      data: {
        userId: contractor2.id,
        partnerId: partner2.id,
        period: month,
        leadsAssigned: Math.floor(2 + Math.random() * 4),
        quotesSubmitted: Math.floor(2 + Math.random() * 3),
        contractsWon: baseContracts2,
        revenue: baseRevenue2,
        averageRating: 4.6 + Math.random() * 0.3,
        completionRate: 92 + Math.random() * 7,
        customerSatisfaction: 4.5 + Math.random() * 0.4,
      }
    });
  }
  
  // Create additional contractors for leaderboard
  const contractor3 = await prisma.user.create({
    data: {
      email: 'james.landscape@contractornetwork.com',
      password: hashedPassword,
      firstName: 'James',
      lastName: 'Wilson',
      name: 'James Wilson',
      role: 'CONTRACTOR',
      companyName: 'GreenScape Landscaping',
      phone: '+1-555-0108',
      address: '888 Garden Blvd',
      city: 'Austin',
      state: 'TX',
      country: 'USA',
      zipCode: '78706',
      trustScore: 91.5,
      isActive: true,
    }
  });

  const partner3 = await prisma.partner.create({
    data: {
      userId: contractor3.id,
      companyName: 'GreenScape Landscaping',
      licenseNumber: 'TX-LAND-2024-003',
      licenseExpiry: new Date('2025-10-31'),
      services: ['Landscaping', 'Irrigation', 'Lawn Care'],
      serviceAreas: ['Austin', 'Round Rock', 'Georgetown'],
      isVerified: true,
      verificationStatus: 'VERIFIED',
      businessAddress: '888 Garden Blvd, Austin, TX 78706',
      businessPhone: '+1-555-0108',
      website: 'https://greenscapelandscaping.com',
      description: 'Professional landscaping and irrigation services for residential and commercial properties.',
    }
  });

  const contractor4 = await prisma.user.create({
    data: {
      email: 'maria.hvac@contractornetwork.com',
      password: hashedPassword,
      firstName: 'Maria',
      lastName: 'Garcia',
      name: 'Maria Garcia',
      role: 'CONTRACTOR',
      companyName: 'Cool Comfort HVAC',
      phone: '+1-555-0109',
      address: '999 Climate Control Dr',
      city: 'San Antonio',
      state: 'TX',
      country: 'USA',
      zipCode: '78201',
      trustScore: 93.8,
      isActive: true,
    }
  });

  const partner4 = await prisma.partner.create({
    data: {
      userId: contractor4.id,
      companyName: 'Cool Comfort HVAC',
      licenseNumber: 'TX-HVAC-2024-004',
      licenseExpiry: new Date('2025-09-30'),
      services: ['HVAC Installation', 'HVAC Repair', 'Maintenance'],
      serviceAreas: ['San Antonio', 'Austin', 'New Braunfels'],
      isVerified: true,
      verificationStatus: 'VERIFIED',
      businessAddress: '999 Climate Control Dr, San Antonio, TX 78201',
      businessPhone: '+1-555-0109',
      website: 'https://coolcomforthvac.com',
      description: 'Expert HVAC installation, repair, and maintenance services with 24/7 emergency support.',
    }
  });

  const contractor5 = await prisma.user.create({
    data: {
      email: 'tom.electric@contractornetwork.com',
      password: hashedPassword,
      firstName: 'Tom',
      lastName: 'Anderson',
      name: 'Tom Anderson',
      role: 'CONTRACTOR',
      companyName: 'Bright Spark Electrical',
      phone: '+1-555-0110',
      address: '111 Voltage Lane',
      city: 'Dallas',
      state: 'TX',
      country: 'USA',
      zipCode: '75204',
      trustScore: 89.2,
      isActive: true,
    }
  });

  const partner5 = await prisma.partner.create({
    data: {
      userId: contractor5.id,
      companyName: 'Bright Spark Electrical',
      licenseNumber: 'TX-ELEC-2024-005',
      licenseExpiry: new Date('2025-08-31'),
      services: ['Electrical Installation', 'Electrical Repair', 'Panel Upgrades'],
      serviceAreas: ['Dallas', 'Fort Worth', 'Plano'],
      isVerified: true,
      verificationStatus: 'VERIFIED',
      businessAddress: '111 Voltage Lane, Dallas, TX 75204',
      businessPhone: '+1-555-0110',
      website: 'https://brightsparkelectrical.com',
      description: 'Licensed electrical contractors specializing in residential and light commercial projects.',
    }
  });

  // Add performance data for additional contractors
  for (const month of months) {
    // Contractor 3 - GreenScape Landscaping
    await prisma.contractorPerformance.create({
      data: {
        userId: contractor3.id,
        partnerId: partner3.id,
        period: month,
        leadsAssigned: Math.floor(4 + Math.random() * 6),
        quotesSubmitted: Math.floor(3 + Math.random() * 5),
        contractsWon: Math.floor(2 + Math.random() * 4),
        revenue: 35000 + Math.random() * 25000,
        averageRating: 4.4 + Math.random() * 0.4,
        completionRate: 88 + Math.random() * 10,
        customerSatisfaction: 4.2 + Math.random() * 0.6,
      }
    });

    // Contractor 4 - Cool Comfort HVAC
    await prisma.contractorPerformance.create({
      data: {
        userId: contractor4.id,
        partnerId: partner4.id,
        period: month,
        leadsAssigned: Math.floor(5 + Math.random() * 7),
        quotesSubmitted: Math.floor(4 + Math.random() * 6),
        contractsWon: Math.floor(3 + Math.random() * 5),
        revenue: 42000 + Math.random() * 33000,
        averageRating: 4.5 + Math.random() * 0.4,
        completionRate: 91 + Math.random() * 7,
        customerSatisfaction: 4.4 + Math.random() * 0.5,
      }
    });

    // Contractor 5 - Bright Spark Electrical
    await prisma.contractorPerformance.create({
      data: {
        userId: contractor5.id,
        partnerId: partner5.id,
        period: month,
        leadsAssigned: Math.floor(3 + Math.random() * 5),
        quotesSubmitted: Math.floor(2 + Math.random() * 4),
        contractsWon: Math.floor(2 + Math.random() * 3),
        revenue: 30000 + Math.random() * 20000,
        averageRating: 4.3 + Math.random() * 0.4,
        completionRate: 86 + Math.random() * 11,
        customerSatisfaction: 4.1 + Math.random() * 0.7,
      }
    });
  }
  
  // Quarterly records
  await prisma.contractorPerformance.create({
    data: {
      userId: contractor1.id,
      partnerId: partner1.id,
      period: '2024-Q2',
      leadsAssigned: 15,
      quotesSubmitted: 12,
      contractsWon: 8,
      revenue: 185000.00,
      averageRating: 4.7,
      completionRate: 95.5,
      customerSatisfaction: 4.6,
    }
  });

  await prisma.contractorPerformance.create({
    data: {
      userId: contractor2.id,
      partnerId: partner2.id,
      period: '2024-Q2',
      leadsAssigned: 8,
      quotesSubmitted: 7,
      contractsWon: 5,
      revenue: 275000.00,
      averageRating: 4.8,
      completionRate: 98.2,
      customerSatisfaction: 4.9,
    }
  });

  // Create export attempts
  console.log('📤 Creating export attempts...');
  
  await prisma.exportAttempt.create({
    data: {
      userId: adminUser.id,
      entityType: 'lead',
      entityId: lead1.id,
      destination: 'Salesforce CRM',
      status: 'COMPLETED',
      exportData: {
        leadId: lead1.id,
        customerName: 'Jennifer Wilson',
        services: ['Roofing'],
        value: 31429.41
      },
      response: {
        success: true,
        crmLeadId: 'SF-LEAD-001',
        message: 'Lead successfully exported to Salesforce'
      },
      completedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000), // 2 days ago
    }
  });

  await prisma.exportAttempt.create({
    data: {
      userId: salesUser1.id,
      entityType: 'quote',
      entityId: quote1.id,
      destination: 'HubSpot CRM',
      status: 'FAILED',
      exportData: {
        quoteId: quote1.id,
        quoteNumber: 'Q2C-2024-0001',
        value: 31429.41
      },
      errorMessage: 'API authentication failed. Invalid credentials.',
    }
  });

  // Create notifications
  console.log('🔔 Creating notifications...');
  
  await prisma.notification.create({
    data: {
      userId: salesUser1.id,
      title: 'New Lead Assigned',
      message: 'You have been assigned a new lead: Jennifer Wilson (Roofing)',
      type: 'LEAD_ASSIGNED',
      metadata: {
        leadId: lead1.id,
        leadName: 'Jennifer Wilson',
        service: 'Roofing'
      }
    }
  });

  await prisma.notification.create({
    data: {
      userId: salesUser2.id,
      title: 'Quote Accepted',
      message: 'Michael Davis has accepted your pool installation quote for $56,160',
      type: 'QUOTE_APPROVED',
      isRead: true,
      readAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000), // 1 day ago
      metadata: {
        quoteId: quote2.id,
        customerName: 'Michael Davis',
        amount: 56160.00
      }
    }
  });

  await prisma.notification.create({
    data: {
      userId: contractor2.id,
      title: 'Contract Signed',
      message: 'Contract CNT-2024-0001 has been signed and is ready to begin',
      type: 'CONTRACT_SIGNED',
      metadata: {
        contractId: contract1.id,
        contractNumber: 'CNT-2024-0001',
        projectType: 'Pool Installation'
      }
    }
  });

  // Create compliance checklist
  await prisma.complianceChecklist.create({
    data: {
      name: 'Pool Installation Compliance',
      description: 'Required compliance items for pool installation projects',
      category: 'Pool Installation',
      isRequired: true,
      checkItems: [
        {
          item: 'Building permit obtained',
          required: true,
          completed: false
        },
        {
          item: 'Electrical permit for pool equipment',
          required: true,
          completed: false
        },
        {
          item: 'Fence/barrier compliance check',
          required: true,
          completed: false
        },
        {
          item: 'Insurance certificate on file',
          required: true,
          completed: true
        },
        {
          item: 'Final inspection scheduled',
          required: true,
          completed: false
        }
      ]
    }
  });

  // Create system settings
  await prisma.systemSettings.upsert({
    where: { key: 'lead_scoring_weights' },
    update: {
      value: {
        budget: 0.3,
        timeline: 0.25,
        source: 0.2,
        services: 0.15,
        location: 0.1
      }
    },
    create: {
      key: 'lead_scoring_weights',
      value: {
        budget: 0.3,
        timeline: 0.25,
        source: 0.2,
        services: 0.15,
        location: 0.1
      }
    }
  });

  await prisma.systemSettings.upsert({
    where: { key: 'quote_validity_days' },
    update: {
      value: {
        roofing: 30,
        pools: 45,
        gutters: 15,
        irrigation: 20
      }
    },
    create: {
      key: 'quote_validity_days',
      value: {
        roofing: 30,
        pools: 45,
        gutters: 15,
        irrigation: 20
      }
    }
  });

  // Create audit logs for key actions
  console.log('📝 Creating audit logs...');
  
  await prisma.auditLog.create({
    data: {
      userId: salesUser2.id,
      entityType: 'quote',
      entityId: quote2.id,
      action: 'accept',
      oldData: { status: 'SENT', isAccepted: false },
      newData: { status: 'ACCEPTED', isAccepted: true },
      metadata: {
        customerEmail: 'michael.davis@outlook.com',
        acceptedAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000)
      },
      ipAddress: '192.168.1.100',
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
  });

  await prisma.auditLog.create({
    data: {
      userId: contractor2.id,
      entityType: 'contract',
      entityId: contract1.id,
      action: 'sign',
      oldData: { status: 'PENDING_SIGNATURE' },
      newData: { status: 'ACTIVE', signedAt: new Date() },
      metadata: {
        contractNumber: 'CNT-2024-0001',
        signatureMethod: 'digital'
      },
      ipAddress: '192.168.1.101',
      userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15'
    }
  });

  // Create Pricing Rates
  console.log('💵 Creating pricing rates...');
  
  await prisma.pricingRate.createMany({
    data: [
      {
        serviceType: 'roof',
        rate: 85,
        unit: 'sq m',
        currency: 'ZAR',
        isActive: true,
        description: 'Base rate for roofing work per square meter'
      },
      {
        serviceType: 'pool',
        rate: 120,
        unit: 'sq m',
        currency: 'ZAR',
        isActive: true,
        description: 'Pool installation/maintenance per square meter'
      },
      {
        serviceType: 'gutter',
        rate: 45,
        unit: 'lm',
        currency: 'ZAR',
        isActive: true,
        description: 'Gutter installation per linear meter'
      },
      {
        serviceType: 'irrigation',
        rate: 95,
        unit: 'sq m',
        currency: 'ZAR',
        isActive: true,
        description: 'Irrigation system per square meter'
      },
      {
        serviceType: 'solar_panels',
        rate: 150,
        unit: 'sq m',
        currency: 'ZAR',
        isActive: true,
        description: 'Solar panel installation per square meter'
      },
      {
        serviceType: 'perimeter_walls',
        rate: 55,
        unit: 'lm',
        currency: 'ZAR',
        isActive: true,
        description: 'Perimeter wall construction per linear meter'
      },
      {
        serviceType: 'paving',
        rate: 75,
        unit: 'sq m',
        currency: 'ZAR',
        isActive: true,
        description: 'Paving work per square meter'
      }
    ]
  });

  console.log('✅ Database seed completed successfully!');
  console.log('\n📊 Summary of created data:');
  console.log(`👤 Users: ${await prisma.user.count()}`);
  console.log(`🤝 Partners: ${await prisma.partner.count()}`);
  console.log(`👥 Customers: ${await prisma.customer.count()}`);
  console.log(`📋 Leads: ${await prisma.lead.count()}`);
  console.log(`💰 Quotes: ${await prisma.quote.count()}`);
  console.log(`📄 Contracts: ${await prisma.contract.count()}`);
  console.log(`⏰ SLA Tracking: ${await prisma.sLATracking.count()}`);
  console.log(`📤 Export Attempts: ${await prisma.exportAttempt.count()}`);
  console.log(`🔔 Notifications: ${await prisma.notification.count()}`);
  console.log(`📊 Performance Records: ${await prisma.contractorPerformance.count()}`);
  console.log(`📝 Audit Logs: ${await prisma.auditLog.count()}`);
  console.log(`💵 Pricing Rates: ${await prisma.pricingRate.count()}`);
  
  console.log('\n🔐 Test Account Credentials:');
  console.log('Admin: admin@quote2contract.com / admin123');
  console.log('Default Test: john@doe.com / johndoe123');
  console.log('Sales: sarah.johnson@quote2contract.com / johndoe123');
  console.log('Contractor: david.roofing@contractornetwork.com / johndoe123');
  console.log('Customer: emily.homeowner@gmail.com / johndoe123');
}

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