import mongoose from 'mongoose';
import Series from '../server/models/series.js';
import Event from '../server/models/event.js';

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/ghostguild';

async function mergeSeries() {
  try {
    await mongoose.connect(MONGODB_URI);
    console.log('Connected to MongoDB');

    // Get both series
    const oldSeries = await Series.findOne({ id: 'cooperative-values-into-practice' });
    const newSeries = await Series.findOne({ id: 'coop-values-into-practice-2025' });

    console.log(`\nOld series _id: ${oldSeries?._id || 'NOT FOUND'}`);
    console.log(`New series _id: ${newSeries?._id || 'NOT FOUND'}`);

    if (!oldSeries) {
      console.log('\nError: Old series not found!');
      return;
    }

    // Update the old series with new ticketing and metadata
    oldSeries.tickets = {
      enabled: true,
      requiresSeriesTicket: false,
      allowIndividualEventTickets: true,
      currency: 'CAD',
      member: {
        available: true,
        isFree: true,
        price: 0,
        name: 'Member Series Pass',
        description: 'Free access to all sessions in the Cooperative Values into Practice series for Ghost Guild members.'
      },
      public: {
        available: true,
        name: 'Series Pass',
        description: 'Access to all 6 sessions in the Cooperative Values into Practice series',
        price: 150,
        quantity: 20,
        sold: 0,
        reserved: 0
      },
      capacity: {
        total: 30,
        reserved: 0
      },
      waitlist: {
        enabled: true,
        maxSize: 15,
        entries: []
      }
    };
    oldSeries.targetCircles = ['founder', 'practitioner'];
    oldSeries.totalEvents = 6;
    
    await oldSeries.save();
    console.log('\n✓ Updated old series with new configuration');

    // Update all new events to use the old series ID
    const result = await Event.updateMany(
      { 'series.id': 'coop-values-into-practice-2025' },
      { 
        $set: { 
          'series.id': 'cooperative-values-into-practice',
          'tickets.seriesTicketReference': oldSeries._id
        }
      }
    );

    console.log(`✓ Updated ${result.modifiedCount} events to use series ID: cooperative-values-into-practice`);

    // Delete the new duplicate series
    if (newSeries) {
      await Series.deleteOne({ id: 'coop-values-into-practice-2025' });
      console.log('✓ Deleted duplicate series: coop-values-into-practice-2025');
    }

    // Verify
    const events = await Event.find({ 
      'series.id': 'cooperative-values-into-practice',
      'series.isSeriesEvent': true
    }).select('title series.position startDate').sort({ 'series.position': 1 });

    console.log(`\n✅ Series now has ${events.length} events:`);
    events.forEach(e => {
      console.log(`  ${e.series.position}. ${e.title} - ${e.startDate.toLocaleDateString()}`);
    });

  } catch (error) {
    console.error('Error:', error);
  } finally {
    await mongoose.connection.close();
  }
}

mergeSeries();
