import mysql from 'mysql2/promise';
import dotenv from 'dotenv';

dotenv.config();

async function migrate() {
    const connection = await mysql.createConnection({
        host: process.env.DB_HOST,
        user: process.env.DB_USER,
        password: process.env.DB_PASS,
        database: process.env.DB_NAME,
        port: parseInt(process.env.DB_PORT || '3306')
    });

    try {
        console.log('🚀 ' + 'Starting migration: asset_server (서버PC) -> asset_pc');

        // 1. 서버PC 데이터 조회
        const [serverPcs] = await connection.query(
            "SELECT * FROM asset_server WHERE asset_type = '서버PC'"
        );

        if (serverPcs.length === 0) {
            console.log('✅ ' + 'No ServerPC assets found in asset_server table.');
            return;
        }

        console.log(`📦 Found ${serverPcs.length} ServerPC assets to migrate.`);

        // 2. asset_pc 컬럼 정보 조회
        const [pcColumnsRows] = await connection.query('DESCRIBE asset_pc');
        const pcColumns = pcColumnsRows.map(r => r.Field);
        console.log('📋 Target columns:', pcColumns);

        // 3. asset_pc 테이블로 이동 (category를 'PC'로 변경)
        for (const asset of serverPcs) {
            const dataToInsert = {};
            
            // 공통 컬럼 매핑
            pcColumns.forEach(col => {
                if (col === 'category') {
                    dataToInsert[col] = 'PC';
                } else if (asset.hasOwnProperty(col)) {
                    dataToInsert[col] = asset[col];
                }
            });

            // 특수한 매핑 (예: model_name -> asset_pc에 컬럼이 없다면 memo에 추가하거나 무시)
            // 현재 asset_pc에는 model_name이 없으므로 memo에 보존하는 것이 안전함
            if (asset.model_name) {
                const currentMemo = dataToInsert.memo || '';
                dataToInsert.memo = `[모델명: ${asset.model_name}] ${currentMemo}`.trim();
            }

            const columns = Object.keys(dataToInsert).map(col => `\`${col}\``).join(', ');
            const placeholders = Object.keys(dataToInsert).map(() => '?').join(', ');
            const values = Object.values(dataToInsert);

            await connection.query(
                `INSERT INTO asset_pc (${columns}) VALUES (${placeholders})`,
                values
            );
            console.log(`  - Migrated: ${asset.asset_code || asset.id}`);
        }

        // 4. asset_server 테이블에서 삭제
        const [deleteResult] = await connection.query(
            "DELETE FROM asset_server WHERE asset_type = '서버PC'"
        );
        console.log(`🗑️ Deleted ${deleteResult.affectedRows} records from asset_server.`);

        console.log('🎉 Migration completed successfully!');

    } catch (err) {
        console.error('❌ Migration failed:', err);
    } finally {
        await connection.end();
    }
}

migrate();
