/**
 * Excel → MySQL Import
 * - importiert ALLE Sheets
 * - Sheet-Name wird als Kategorie gespeichert
 * - Preise robust (Number, "55,00 €", Text, leer)
 */

const xlsx = require("xlsx");
const db = require("./db");

// ===============================
// KONFIG
// ===============================
const FILE_PATH = "2024091001 Preisliste PRAXIS.xlsx";

// ===============================
// HILFSFUNKTIONEN
// ===============================
function getColumn(row, name) {
    const key = Object.keys(row).find(k =>
        k.toLowerCase().includes(name.toLowerCase())
    );
    return key ? row[key] : undefined;
}

function parsePrice(value) {
    if (value === undefined || value === null) return 0.00;

    // Excel-Währungsfeld → Number
    if (typeof value === "number") {
        return value;
    }

    // String → Zahl extrahieren
    if (typeof value === "string") {
        const cleaned = value
            .replace(",", ".")
            .replace(/[^\d.]/g, "");

        const parsed = parseFloat(cleaned);
        return isNaN(parsed) ? 0.00 : parsed;
    }

    return 0.00;
}

// ===============================
// START
// ===============================
console.log("📄 Lese Excel-Datei …");

const workbook = xlsx.readFile(FILE_PATH);
const sheetNames = workbook.SheetNames;

console.log(`📑 ${sheetNames.length} Sheets gefunden:`, sheetNames);

// ===============================
// IMPORT ALLER SHEETS
// ===============================
sheetNames.forEach(sheetName => {

    console.log(`➡️ Importiere Sheet: "${sheetName}"`);

    const sheet = workbook.Sheets[sheetName];
    const rows = xlsx.utils.sheet_to_json(sheet);

    console.log(`   ↳ ${rows.length} Zeilen gefunden`);

    rows.forEach((row, index) => {

        // ===============================
        // TEXTFELDER
        // ===============================
        const name_de = getColumn(row, "deutsch")
            ? getColumn(row, "deutsch").toString().trim()
            : "--";

        const name_es = getColumn(row, "spanisch")
            ? getColumn(row, "spanisch").toString().trim()
            : "--";

        // ===============================
        // PREISE
        // ===============================
        const price = parsePrice(getColumn(row, "preis"));
        const price_c70 = parsePrice(getColumn(row, "c70"));

        // ===============================
        // INSERT
        // ===============================
        db.query(
            `
            INSERT INTO services
            (name_de, name_es, category, price, price_c70)
            VALUES (?, ?, ?, ?, ?)
            `,
            [
                name_de,
                name_es,
                sheetName,   // 👈 Kategorie = Sheet-Name
                price,
                price_c70
            ],
            err => {
                if (err) {
                    console.error(
                        `❌ Fehler in Sheet "${sheetName}", Zeile ${index + 2}:`,
                        err.message
                    );
                }
            }
        );
    });
});

console.log("✅ Import aller Sheets abgeschlossen");
