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 fixSeriesId() {
  try {
    await mongoose.connect(MONGODB_URI);
    console.log('Connected to MongoDB');

    // Check existing series
    const allSeries = await Series.find({}).select('id title').lean();
    console.log('\nExisting series:');
    allSeries.forEach(s => console.log(`  - ${s.id}: ${s.title}`));

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

    // Update the old series with new data
    const updatedSeries = await Series.findOneAndUpdate(
      { id: 'cooperative-values-into-practice' },
      {
        title: 'Cooperative Values into Practice',
        description: 'A practical, region-agnostic foundation in cooperative values and governance for game studio founders interested in worker-centric, anti-capitalist models. Structured as a peer-driven workshop emphasizing reciprocal learning and sharing.',
        type: 'workshop_series',
        isVisible: true,
        isActive: true,
        targetCircles: ['founder', 'practitioner'],
        totalEvents: 6,
        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
          },
          capacity: {
            total: 30
          },
          waitlist: {
            enabled: true,
            maxSize: 15
          }
        }
      },
      { new: true }
    );

    console.log('✓ Updated existing series');

    // Update all the 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',
          'seriesTicketReference': updatedSeries._id
        }
      }
    );

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

    // Verify the events
    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✓ Found ${events.length} events in the series:`);
    events.forEach(e => {
      console.log(`  ${e.series.position}. ${e.title} - ${e.startDate.toLocaleDateString()}`);
    });

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

fixSeriesId();
