/**
 * Migration script to add new support management features
 * Run this script after deploying the new support management system
 */

const mongoose = require('mongoose');
const Ticket = require('../models/ticket.model.js');
const CallbackRequest = require('../models/callback-request.model.js');

async function migrateTickets() {
    try {
        console.log('🚀 Starting ticket migration...');
        
        // Add new fields to existing tickets (driver tickets)
        const result = await Ticket.updateMany(
            { 
                $or: [
                    { priority: { $exists: false } },
                    { escalated: { $exists: false } },
                    { creatorType: { $exists: false } }
                ]
            },
            {
                $set: {
                    creatorType: 'driver', // Existing tickets are driver tickets
                    priority: 'normal',
                    escalated: false,
                    escalatedAt: null,
                    escalatedBy: null,
                    assignedTo: null,
                    assignedType: null,
                    assignedBy: null,
                    assignedAt: null,
                    subject: null,
                    user: null,
                    booking: null
                }
            }
        );
        
        console.log(`✅ Updated ${result.modifiedCount} tickets with new fields`);
        
        // Add isInternal: false to existing messages
        const messageResult = await Ticket.updateMany(
            { 'messages.isInternal': { $exists: false } },
            {
                $set: {
                    'messages.$[].isInternal': false
                }
            }
        );
        
        console.log(`✅ Updated messages in ${messageResult.modifiedCount} tickets`);
        
        console.log('🎉 Ticket migration completed successfully!');
        
    } catch (error) {
        console.error('❌ Ticket migration failed:', error);
        throw error;
    }
}

async function migrateCallbackRequests() {
    try {
        console.log('🚀 Starting callback request migration...');
        
        // Add new fields to existing callback requests
        const result = await CallbackRequest.updateMany(
            { 
                $or: [
                    { name: { $exists: false } },
                    { reasonCategory: { $exists: false } }
                ]
            },
            {
                $set: {
                    name: '',
                    reasonCategory: 'General Inquiry'
                }
            }
        );
        
        console.log(`✅ Updated ${result.modifiedCount} callback requests with new fields`);
        console.log('🎉 Callback request migration completed successfully!');
        
    } catch (error) {
        console.error('❌ Callback request migration failed:', error);
        throw error;
    }
}

async function runMigration() {
    await migrateTickets();
    await migrateCallbackRequests();
}

// Run migration if called directly
if (require.main === module) {
    // Connect to database
    require('dotenv').config();
    
    mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/cab-booking')
        .then(() => {
            console.log('📦 Connected to MongoDB');
            return runMigration();
        })
        .then(() => {
            console.log('✨ All migrations completed!');
            process.exit(0);
        })
        .catch((error) => {
            console.error('💥 Error:', error);
            process.exit(1);
        });
}

module.exports = { migrateTickets, migrateCallbackRequests, runMigration };