import fs from 'fs';
import path from 'path';
import mongoose from 'mongoose';
import dotenv from 'dotenv';

// Import Models
import Project from '../models/Project.js';
import Part from '../models/Part.js';
import PaintingScheme from '../models/PaintingScheme.js';
import ApplicationRecord from '../models/ApplicationRecord.js';
import Inspection from '../models/Inspection.js';
import TechnicalDataSheet from '../models/TechnicalDataSheet.js';
import YieldStudy from '../models/YieldStudy.js';

dotenv.config();

const DATA_DIR = path.join(process.cwd(), 'data');

const readJson = (filename: string) => {
    const filePath = path.join(DATA_DIR, filename);
    if (!fs.existsSync(filePath)) return [];
    return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
};

const migrate = async () => {
    try {
        const uri = process.env.MONGODB_URI;
        if (!uri) throw new Error('MONGODB_URI not defined');
        await mongoose.connect(uri);
        console.log('Connected to MongoDB for migration...');

        const idMap = new Map<string, mongoose.Types.ObjectId>();

        // 1. TechnicalDataSheets
        console.log('Migrating TechnicalDataSheets...');
        const datasheets = readJson('datasheets.json');
        for (const ds of datasheets) {
            const newDs = new TechnicalDataSheet({
                ...ds,
                _id: new mongoose.Types.ObjectId()
            });
            await newDs.save();
            idMap.set(ds.id, newDs._id as mongoose.Types.ObjectId);
        }

        // 2. Projects
        console.log('Migrating Projects...');
        const projects = readJson('projects.json');
        for (const p of projects) {
            const newP = new Project({
                ...p,
                _id: new mongoose.Types.ObjectId()
            });
            await newP.save();
            idMap.set(p.id, newP._id as mongoose.Types.ObjectId);
        }

        // 3. Parts
        console.log('Migrating Parts...');
        const parts = readJson('parts.json');
        for (const part of parts) {
            const projectId = idMap.get(part.projectId);
            if (projectId) {
                const newPart = new Part({ ...part, projectId });
                await newPart.save();
            }
        }

        // 4. PaintingSchemes
        console.log('Migrating PaintingSchemes...');
        const schemes = readJson('paintingSchemes.json');
        for (const s of schemes) {
            const projectId = idMap.get(s.projectId);
            if (projectId) {
                const newS = new PaintingScheme({ ...s, projectId });
                await newS.save();
            }
        }

        // 5. ApplicationRecords
        console.log('Migrating ApplicationRecords...');
        const records = readJson('applicationRecords.json');
        for (const r of records) {
            const projectId = idMap.get(r.projectId);
            if (projectId) {
                const newR = new ApplicationRecord({ ...r, projectId });
                await newR.save();
            }
        }

        // 6. Inspections
        console.log('Migrating Inspections...');
        const inspections = readJson('inspections.json');
        for (const i of inspections) {
            const projectId = idMap.get(i.projectId);
            if (projectId) {
                const newI = new Inspection({ ...i, projectId });
                await newI.save();
            }
        }

        // 7. YieldStudies
        console.log('Migrating YieldStudies...');
        const studies = readJson('yield_studies.json');
        for (const s of studies) {
            const dataSheetId = idMap.get(s.dataSheetId);
            if (dataSheetId) {
                const newS = new YieldStudy({ ...s, dataSheetId });
                await newS.save();
            }
        }

        console.log('✅ Migration completed successfully!');
        process.exit(0);
    } catch (error) {
        console.error('❌ Migration failed:', error);
        process.exit(1);
    }
};

migrate();
