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

    // Delete the incorrectly named series
    await Series.deleteOne({ id: 'coop-values-into-practice-2025' });
    console.log('✓ Deleted old series');

    // Create series with the correct ID that matches the old event
    const series = new Series({
      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,
      createdBy: 'admin@ghostguild.org',
      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 for Ghost Guild members.'
        },
        public: {
          available: true,
          name: 'Series Pass',
          description: 'Access to all 6 sessions',
          price: 150,
          quantity: 20,
          sold: 0,
          reserved: 0
        },
        capacity: {
          total: 30,
          reserved: 0
        },
        waitlist: {
          enabled: true,
          maxSize: 15,
          entries: []
        }
      }
    });

    await series.save();
    console.log('✓ Created series with ID: cooperative-values-into-practice');

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

    console.log(`✓ Updated ${result.modifiedCount} events`);

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

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

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

createCorrectSeries();
