import mongoose from 'mongoose';
import { WorkOrder } from '../models/WorkOrder';
import { Project } from '../models/Project';
import { Asset } from '../models/Asset';
import { User } from '../models/User';
import { Company } from '../models/Company';
import { connectDatabase, disconnectDatabase } from '../config/database';

async function seedWorkOrders() {
    try {
        await connectDatabase();
        console.log('🌱 Starting Work Order seeding...');

        // 0. Consolidate collections if they exist
        const db = mongoose.connection.db;
        if (db) {
            const collections = await db.listCollections().toArray();
            const colNames = collections.map(c => c.name);

            if (colNames.includes('workorders') && colNames.includes('workOrders')) {
                console.log('🧹 Both "workorders" and "workOrders" exist. Consolidating into "workOrders"...');
                await db.collection('workorders').drop();
                console.log('🗑️ Dropped legacy "workorders" collection.');
            } else if (colNames.includes('workorders')) {
                console.log('🔄 Renaming "workorders" to "workOrders" for consistency...');
                await db.collection('workorders').rename('workOrders');
            }
        }

        // 1. Ensure project 's1' exists
        let projectS1 = await Project.findOne({ code: 's1' });
        if (!projectS1) {
            console.log('📝 Project "s1" not found. Creating it...');
            let company: any = await Company.findOne().lean();
            if (!company) {
                console.log('📝 No company found, creating one...');
                const newCompany = await Company.create({
                    _id: 'c1', // Providing string ID explicitly
                    name: 'VuPhong Energy Group',
                    code: 'VPEG',
                    status: 'active'
                });
                company = newCompany.toObject();
            }

            const companyId = company?._id || company?.id;
            console.log(`🏢 Using company: ${company?.name || 'N/A'} (ID: ${companyId})`);

            projectS1 = await Project.create({
                _id: 's1', // Providing string ID explicitly
                companyId: companyId,
                name: 'VPEG Ninh Thuận Solar Site',
                code: 's1',
                location: {
                    address: 'Khu công nghiệp Ninh Thuận, Việt Nam',
                    coordinates: { lat: 11.5626, lng: 108.9602 }
                },
                capacityMWp: 1.5,
                commissioningDate: new Date('2023-01-01'),
                status: 'operational'
            });
            console.log('✅ Created project "s1"');
        }

        // 2. Fetch dependencies
        const users = await User.find().limit(20);
        if (users.length === 0) {
            console.error('❌ No users found. Please seed users first.');
            process.exit(1);
        }

        // 3. Ensure assets exist for project 's1'
        let assets = await Asset.find({ projectId: projectS1._id });
        if (assets.length === 0) {
            console.log('📝 No assets found for "s1". Reassigning any existing assets or creating new ones...');
            const anyAssets = await Asset.find().limit(5);
            if (anyAssets.length > 0) {
                for (const asset of anyAssets) {
                    asset.projectId = projectS1._id as any;
                    await asset.save();
                }
                assets = anyAssets;
                console.log(`♻️ Reassigned ${anyAssets.length} assets to "s1"`);
            } else {
                const newAssets = [
                    { _id: 'a1', name: 'Inverter Ninja-X1', code: 'INV-01', assetType: 'Inverter', status: 'active', projectId: projectS1._id },
                    { _id: 'a2', name: 'Inverter Ninja-X2', code: 'INV-02', assetType: 'Inverter', status: 'active', projectId: projectS1._id },
                    { _id: 'a3', name: 'Combiner Box LV-1', code: 'CB-01', assetType: 'Combiner Box', status: 'active', projectId: projectS1._id },
                    { _id: 'a4', name: 'Weather Sensor Pro', code: 'WS-01', assetType: 'Weather Station', status: 'active', projectId: projectS1._id }
                ];
                assets = await Asset.insertMany(newAssets) as any;
                console.log('✅ Created 4 new assets for "s1"');
            }
        }

        const technicians = users.filter((u: any) => u.role === 'Technician');
        const supervisors = users.filter((u: any) => ['O&M Manager', 'System Administrator', 'Asset Owner'].includes(u.role));

        const types: ('PM' | 'CM' | 'Cleaning' | 'Inspection' | 'Upgrade')[] = ['PM', 'CM', 'Cleaning', 'Inspection', 'Upgrade'];
        const statuses: ('Draft' | 'Approved' | 'InProgress' | 'Completed' | 'Cancelled' | 'Verified')[] = ['Draft', 'Approved', 'InProgress', 'Completed', 'Verified'];
        const priorities: ('Low' | 'Medium' | 'High')[] = ['Low', 'Medium', 'High'];

        console.log(`🚀 Generating 20 work orders for project ${projectS1.name}...`);
        const demoWorkOrders = [];

        for (let i = 1; i <= 20; i++) {
            const asset = assets[Math.floor(Math.random() * assets.length)];
            const type = types[Math.floor(Math.random() * types.length)];
            const status = statuses[Math.floor(Math.random() * statuses.length)];
            const priority = priorities[Math.floor(Math.random() * priorities.length)];

            const technician = technicians.length > 0 ? technicians[Math.floor(Math.random() * technicians.length)] : users[0];
            const supervisor = supervisors.length > 0 ? supervisors[Math.floor(Math.random() * supervisors.length)] : users[0];

            const scheduledStart = new Date();
            scheduledStart.setDate(scheduledStart.getDate() + (Math.floor(Math.random() * 60) - 30));
            const scheduledEnd = new Date(scheduledStart);
            scheduledEnd.setHours(scheduledEnd.getHours() + 4);

            demoWorkOrders.push({
                _id: `wo-demo-${i}`, // Explicit string ID
                woCode: `WO-${new Date().getFullYear() % 100}${String(i).padStart(4, '0')}`,
                projectId: projectS1._id,
                assetId: asset._id,
                workOrderType: type,
                title: `${type} Maintenance - ${asset.name}`,
                description: `Yêu cầu thực hiện ${type} cho thiết bị ${asset.code}. Kiểm tra định kỳ và record các thông số kỹ thuật.`,
                status: status === 'InProgress' ? 'In Progress' : status, // Fix for UI
                priority: priority,
                scheduledStart,
                scheduledEnd,
                assignedTechnicianId: (technician as any)._id,
                supervisorId: (supervisor as any)._id,
                costLabor: Math.floor(Math.random() * 1000000) + 200000,
                costMaterial: Math.floor(Math.random() * 500000) + 50000,
                costExternal: 0,
                checklistProgress: (status === 'Completed' || status === 'Verified') ? 100 : Math.floor(Math.random() * 90),

                // Fields required by Frontend UI (Legacy/Flat structure)
                siteId: 's1',
                assignedTo: (technician as any).name,
                type: type,
                scheduledDate: scheduledStart.toISOString(),
                createdAt: new Date(),
                updatedAt: new Date()
            });
        }

        // Clean up project 's1' work orders before seeding
        await WorkOrder.deleteMany({ $or: [{ projectId: projectS1._id }, { siteId: 's1' }] });

        const result = await WorkOrder.insertMany(demoWorkOrders);
        console.log(`✅ Successfully seeded ${result.length} Work Orders for project "s1".`);

        await disconnectDatabase();
    } catch (error) {
        console.error('❌ Error seeding Work Orders:', error);
        process.exit(1);
    }
}

seedWorkOrders();
