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', 'jobPost', 'aiWebsite'], // First website submission, job post, AI website
      validFrom: new Date(),
      validUntil: new Date('2026-02-28T23:59:59Z'),
      maxUsage: 10000, // 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'], // Second website submission
      validFrom: new Date(),
      validUntil: new Date('2026-02-28T23:59:59Z'),
      maxUsage: 10000,
      isActive: true,
    };

    const coupons = [nocostWebsite, fwf01];

    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, job post, and AI website (100% off)');
    console.log('   2. FWF01 - 70% off second website submission');
    console.log('\n✨ All coupons valid until February 28, 2026\n');

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

createCoupons();
