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

const prisma = new PrismaClient();

async function seedPhase2Data() {
  console.log('🌱 Seeding Phase 2 data...');

  try {
    // 1. Seed Materials Catalog
    console.log('📦 Seeding materials catalog...');
    
    const materials = [
      // Roofing Materials
      {
        category: 'roofing',
        name: 'Premium Concrete Roof Tiles',
        description: 'High-quality concrete tiles with excellent durability and weather resistance',
        basePrice: 185,
        unit: 'sq m',
        brand: 'Marley',
        color: 'Charcoal',
        durability: 50,
        warranty: 20,
        features: [
          'Fire resistant',
          'Low maintenance',
          'Energy efficient',
          'UV resistant',
        ],
        tags: ['premium', 'concrete', 'durable'],
        isAvailable: true,
        leadTime: 7,
      },
      {
        category: 'roofing',
        name: 'IBR Steel Sheeting',
        description: 'Galvanized steel roofing sheets with chromadek coating',
        basePrice: 145,
        unit: 'sq m',
        brand: 'ArcelorMittal',
        color: 'Slate Grey',
        durability: 25,
        warranty: 15,
        features: [
          'Lightweight',
          'Quick installation',
          'Rust resistant',
          'Cost effective',
        ],
        tags: ['steel', 'chromadek', 'economical'],
        isAvailable: true,
        leadTime: 3,
      },
      {
        category: 'roofing',
        name: 'Clay Roof Tiles',
        description: 'Traditional clay tiles with natural aesthetics',
        basePrice: 295,
        unit: 'sq m',
        brand: 'Redland',
        color: 'Terracotta',
        durability: 100,
        warranty: 50,
        features: [
          'Natural material',
          'Excellent insulation',
          'Classic appearance',
          'Long-lasting',
        ],
        tags: ['premium', 'clay', 'traditional'],
        isAvailable: true,
        leadTime: 14,
      },

      // Solar Panels
      {
        category: 'solar',
        name: 'Monocrystalline Solar Panel 550W',
        description: 'High-efficiency monocrystalline solar panels',
        basePrice: 4500,
        unit: 'panel',
        brand: 'JA Solar',
        durability: 25,
        warranty: 25,
        features: [
          '21.5% efficiency',
          'PERC technology',
          'Low temperature coefficient',
          'PID resistant',
        ],
        tags: ['solar', 'high-efficiency', 'premium'],
        isAvailable: true,
        leadTime: 10,
      },
      {
        category: 'solar',
        name: 'Polycrystalline Solar Panel 450W',
        description: 'Cost-effective polycrystalline solar solution',
        basePrice: 3200,
        unit: 'panel',
        brand: 'Canadian Solar',
        durability: 25,
        warranty: 20,
        features: [
          '18% efficiency',
          'Reliable performance',
          'Budget-friendly',
          'Proven technology',
        ],
        tags: ['solar', 'economical', 'reliable'],
        isAvailable: true,
        leadTime: 7,
      },

      // Gutters
      {
        category: 'gutters',
        name: 'Aluminium Box Gutter',
        description: 'Seamless aluminium gutters with powder coating',
        basePrice: 285,
        unit: 'lm',
        brand: 'Rheinzink',
        color: 'Anthracite',
        durability: 40,
        warranty: 20,
        features: [
          'Corrosion resistant',
          'Low maintenance',
          'Seamless finish',
          'Multiple colors',
        ],
        tags: ['gutters', 'aluminium', 'premium'],
        isAvailable: true,
        leadTime: 5,
      },

      // Pool
      {
        category: 'pool',
        name: 'Fibreglass Pool Shell - Olympic',
        description: 'Pre-made fibreglass pool shell with smooth finish',
        basePrice: 85000,
        unit: 'unit',
        brand: 'Blue Horizons',
        durability: 30,
        warranty: 15,
        features: [
          '8m x 4m dimensions',
          'Smooth gel coat finish',
          'Chemical resistant',
          'Quick installation',
        ],
        tags: ['pool', 'fibreglass', 'complete'],
        isAvailable: true,
        leadTime: 21,
      },

      // Paving
      {
        category: 'paving',
        name: 'Concrete Interlock Pavers',
        description: 'Durable concrete pavers for driveways and patios',
        basePrice: 195,
        unit: 'sq m',
        brand: 'Corobrik',
        color: 'Charcoal Mix',
        durability: 25,
        warranty: 10,
        features: [
          'High traffic rated',
          'Easy replacement',
          'Various patterns',
          'Non-slip surface',
        ],
        tags: ['paving', 'concrete', 'durable'],
        isAvailable: true,
        leadTime: 5,
      },
    ];

    for (const material of materials) {
      // Check if material exists
      const existing = await prisma.material.findFirst({
        where: { name: material.name },
      });

      if (!existing) {
        await prisma.material.create({
          data: material,
        });
      }
    }

    console.log(`✅ Created ${materials.length} materials`);

    // 2. Seed Contractor Badges
    console.log('🏆 Seeding contractor badges...');

    // Get all partners
    const partners = await prisma.partner.findMany({
      include: { user: true },
    });

    if (partners.length > 0) {
      const badgeTypes: Array<{
        badgeType: 'VERIFIED_CONTRACTOR' | 'LICENSED_PROFESSIONAL' | 'INSURED' | 'TOP_RATED' | 'QUALITY_GUARANTEE';
        name: string;
        description: string;
      }> = [
        {
          badgeType: 'VERIFIED_CONTRACTOR' as const,
          name: 'Verified Contractor',
          description: 'Identity and credentials verified by Quote2Contract',
        },
        {
          badgeType: 'LICENSED_PROFESSIONAL' as const,
          name: 'Licensed Professional',
          description: 'Holds valid professional license',
        },
        {
          badgeType: 'INSURED' as const,
          name: 'Fully Insured',
          description: 'Comprehensive liability and workers compensation insurance',
        },
        {
          badgeType: 'TOP_RATED' as const,
          name: 'Top Rated',
          description: 'Consistently high customer ratings',
        },
        {
          badgeType: 'QUALITY_GUARANTEE' as const,
          name: 'Quality Guarantee',
          description: 'Work backed by quality guarantee',
        },
      ];

      for (const partner of partners) {
        // Give first partner all badges
        if (partner === partners[0]) {
          for (const badge of badgeTypes) {
            await prisma.contractorBadge.create({
              data: {
                contractorId: partner.userId,
                ...badge,
                issuedDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000), // 1 year ago
                expiryDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), // 1 year from now
                isVerified: true,
                verifiedAt: new Date(),
                issuer: 'Quote2Contract',
                isActive: true,
              },
            });
          }
        } else {
          // Give other partners random badges
          const numBadges = Math.floor(Math.random() * 3) + 2; // 2-4 badges
          const shuffled = badgeTypes.sort(() => 0.5 - Math.random());
          const selectedBadges = shuffled.slice(0, numBadges);

          for (const badge of selectedBadges) {
            await prisma.contractorBadge.create({
              data: {
                contractorId: partner.userId,
                ...badge,
                issuedDate: new Date(Date.now() - 180 * 24 * 60 * 60 * 1000), // 6 months ago
                expiryDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000),
                isVerified: true,
                verifiedAt: new Date(),
                issuer: 'Quote2Contract',
                isActive: true,
              },
            });
          }
        }
      }

      console.log(`✅ Created badges for ${partners.length} contractors`);
    }

    // 3. Seed Sample Reviews
    console.log('⭐ Seeding sample reviews...');

    // Get contracts to create reviews for
    const contracts = await prisma.contract.findMany({
      where: { status: 'COMPLETED' },
      take: 10,
    });

    const reviewTemplates = [
      {
        title: 'Excellent workmanship',
        comment: 'The contractor did an outstanding job. Very professional and the quality of work exceeded our expectations. Highly recommend!',
        overallRating: 5,
        qualityRating: 5,
        timelinessRating: 5,
        communicationRating: 5,
        valueRating: 5,
      },
      {
        title: 'Great service',
        comment: 'Very pleased with the work done. The team was professional and completed everything on schedule.',
        overallRating: 4.5,
        qualityRating: 5,
        timelinessRating: 4,
        communicationRating: 4,
        valueRating: 5,
      },
      {
        title: 'Reliable and efficient',
        comment: 'Good quality work at a fair price. Would definitely use again for future projects.',
        overallRating: 4,
        qualityRating: 4,
        timelinessRating: 4,
        communicationRating: 4,
        valueRating: 4,
      },
    ];

    let reviewCount = 0;
    for (const contract of contracts) {
      if (contract.partnerId) {
        const template = reviewTemplates[Math.floor(Math.random() * reviewTemplates.length)];
        
        await prisma.contractorReview.create({
          data: {
            contractId: contract.id,
            contractorId: contract.partnerId,
            customerId: contract.userId,
            ...template,
            isVerified: true,
            verifiedPurchase: true,
            isPublished: true,
            isFeatured: reviewCount < 3, // Make first 3 featured
            helpfulCount: Math.floor(Math.random() * 20),
          },
        });
        
        reviewCount++;
      }
    }

    console.log(`✅ Created ${reviewCount} sample reviews`);

    console.log('\n🎉 Phase 2 seeding completed successfully!');
  } catch (error) {
    console.error('❌ Error seeding Phase 2 data:', error);
    throw error;
  } finally {
    await prisma.$disconnect();
  }
}

// Run if called directly
if (require.main === module) {
  seedPhase2Data()
    .catch((error) => {
      console.error(error);
      process.exit(1);
    });
}

export default seedPhase2Data;
