import mongoose from 'mongoose';
import Coupon from './models/coupon.js';
import dotenv from 'dotenv';

dotenv.config();

const MONGO_URI = process.env.MONGO_URI;

// Connect to MongoDB
mongoose.connect(MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
.then(() => console.log('✅ Connected to MongoDB'))
.catch((err) => {
  console.error('❌ MongoDB connection error:', err);
  process.exit(1);
});

const createCoupons = async () => {
  try {
    console.log('🎫 Creating coupons...\n');

    // Coupon 1: NOCOST - Free first website submission (12.99 USD value)
    const nocostWebsite = {
      code: 'NOCOST',
      discountType: 'free',
      discountAmount: 100, // 100% off
      serviceType: ['websiteSubmission', 'aiWebsite'], // First website submission (free of cost)
      validFrom: new Date(),
      validUntil: new Date('2026-01-30T23:59:59Z'),
      maxUsage: 1000, // Set a reasonable limit
      isActive: true,
    };

    // Coupon 2: FWF01 - 70% off second website submission
    const fwf01 = {
      code: 'FWF01',
      discountType: 'percentage',
      discountAmount: 70, // 70% off
      serviceType: ['websiteSubmission', 'aiWebsite'], // Second website submission
      validFrom: new Date(),
      validUntil: new Date('2026-01-30T23:59:59Z'),
      maxUsage: 1000,
      isActive: true,
    };

    // Coupon 3: NOCOST for Job Post - Free first job vacancy (15.99 USD value)
    const nocostJob = {
      code: 'NOCOST_JOB',
      discountType: 'free',
      discountAmount: 100, // 100% off
      serviceType: ['jobPost'], // Post your first job vacancy
      validFrom: new Date(),
      validUntil: new Date('2026-01-30T23:59:59Z'),
      maxUsage: 1000,
      isActive: true,
    };

    // Coupon 4: Directory submission (6.99 USD value) - free
    const nocostDirectory = {
      code: 'NOCOST_DIR',
      discountType: 'free',
      discountAmount: 100, // 100% off
      serviceType: ['directory'], // Add website to directory
      validFrom: new Date(),
      validUntil: new Date('2026-01-30T23:59:59Z'),
      maxUsage: 1000,
      isActive: true,
    };

    const coupons = [nocostWebsite, fwf01, nocostJob, nocostDirectory];

    for (const couponData of coupons) {
      // Check if coupon already exists
      const existingCoupon = await Coupon.findOne({ code: couponData.code });
      
      if (existingCoupon) {
        console.log(`⚠️  Coupon ${couponData.code} already exists. Updating...`);
        await Coupon.findOneAndUpdate(
          { code: couponData.code },
          couponData,
          { new: true }
        );
        console.log(`✅ Updated coupon: ${couponData.code}`);
      } else {
        const newCoupon = new Coupon(couponData);
        await newCoupon.save();
        console.log(`✅ Created coupon: ${couponData.code}`);
      }
      
      console.log(`   - Type: ${couponData.discountType === 'free' ? 'FREE (100% off)' : couponData.discountAmount + '% off'}`);
      console.log(`   - Services: ${couponData.serviceType.join(', ')}`);
      console.log(`   - Valid until: ${couponData.validUntil.toDateString()}\n`);
    }

    console.log('🎉 All coupons created/updated successfully!\n');
    console.log('📋 Summary of available coupons:');
    console.log('   1. NOCOST - Free first website submission (websiteSubmission, aiWebsite)');
    console.log('   2. FWF01 - 70% off second website submission');
    console.log('   3. NOCOST_JOB - Free first job post');
    console.log('   4. NOCOST_DIR - Free directory submission');
    console.log('\n✨ All coupons valid until January 30, 2026\n');

  } catch (error) {
    console.error('❌ Error creating coupons:', error);
  } finally {
    mongoose.connection.close();
    console.log('🔌 MongoDB connection closed');
  }
};

createCoupons();
