// syncDatabase.js

import { initializeDatabase, syncModelsWithUpdates, syncModelsAlways } from './sequelize.js';
import initializeTypes from './initializeTypes.js';
import initializeSettings from './initializeSettings.js';
import initializeUserRights from './initializeUserRights.js';
import initializeImageTypes from './initializeImageTypes.js';
import initializeFalukant from './initializeFalukant.js';
import setupAssociations from '../models/associations.js';
import models from '../models/index.js';
import { createTriggers } from '../models/trigger.js';
import initializeForum from './initializeForum.js';
import initializeChat from './initializeChat.js';
import initializeMatch3Data from './initializeMatch3.js';
import updateExistingMatch3Levels from './updateExistingMatch3Levels.js';
import initializeTaxi from './initializeTaxi.js';

// Normale Synchronisation (nur bei STAGE=dev Schema-Updates)
const syncDatabase = async () => {
    try {
        // Zeige den aktuellen Stage an
        const currentStage = process.env.STAGE || 'nicht gesetzt';
        console.log(`🚀 Starte Datenbank-Synchronisation (Stage: ${currentStage})`);
        
        if (currentStage !== 'dev') {
            console.log('⚠️  WARNUNG: Automatische Schema-Updates sind deaktiviert');
            console.log('💡 Setze STAGE=dev in der .env Datei für automatische Schema-Updates');
            console.log('🔒 Produktionsmodus: Nur normale Synchronisation ohne Schema-Änderungen');
        } else {
            console.log('✅ Entwicklungsmodus aktiv - Schema-Updates sind aktiviert');
        }

        console.log("Initializing database schemas...");
        await initializeDatabase();  

        console.log("Synchronizing models...");
        await syncModelsWithUpdates(models);

        console.log("Setting up associations...");
        setupAssociations();     

        console.log("Initializing settings...");
        await initializeSettings();

        console.log("Initializing types...");
        await initializeTypes();   

        console.log("Initializing user rights...");
        await initializeUserRights();

        console.log("Initializing image types...");
        await initializeImageTypes();

        console.log("Initializing forums...");
        await initializeForum();     

        console.log("Initializing Falukant...");
        await initializeFalukant();
        
        console.log("Creating triggers...");
        await createTriggers();  

        console.log("Initializing chat...");
        await initializeChat();

        // Match3-Initialisierung NACH der Model-Synchronisation
        console.log("Initializing Match3...");
        await initializeMatch3Data();
        
        // Match3-Levels aktualisieren NACH der Initialisierung
        console.log("Updating existing Match3 levels...");
        await updateExistingMatch3Levels();

        console.log("Initializing Taxi...");
        await initializeTaxi();

        console.log('Database synchronization complete.');
    } catch (error) {
        console.error('Unable to synchronize the database:', error);
    }
};

// Deployment-Synchronisation (immer Schema-Updates)
const syncDatabaseForDeployment = async () => {
    try {
        // Zeige den aktuellen Stage an
        const currentStage = process.env.STAGE || 'nicht gesetzt';
        console.log(`🚀 Starte Datenbank-Synchronisation für Deployment (Stage: ${currentStage})`);
        console.log('✅ Deployment-Modus: Schema-Updates sind immer aktiviert');

        console.log("Initializing database schemas...");
        await initializeDatabase();

        console.log("Synchronizing models with schema updates...");
        await syncModelsAlways(models);

        console.log("Setting up associations...");
        setupAssociations();     

        console.log("Initializing settings...");
        await initializeSettings();

        console.log("Initializing types...");
        await initializeTypes();   

        console.log("Initializing user rights...");
        await initializeUserRights();

        console.log("Initializing image types...");
        await initializeImageTypes();

        console.log("Initializing forums...");
        await initializeForum();     

        console.log("Initializing Falukant...");
        await initializeFalukant();
        
        console.log("Creating triggers...");
        await createTriggers();  

        console.log("Initializing chat...");
        await initializeChat();

        // Match3-Initialisierung NACH der Model-Synchronisation UND nach der Erstellung aller Tabellen
        console.log("Initializing Match3...");
        await initializeMatch3Data();
        
        // Match3-Levels aktualisieren NACH der Initialisierung
        console.log("Updating existing Match3 levels...");
        await updateExistingMatch3Levels();

        console.log("Initializing Taxi...");
        await initializeTaxi();

        console.log('Database synchronization for deployment complete.');
    } catch (error) {
        console.error('Unable to synchronize the database for deployment:', error);
        throw error; // Fehler weiterwerfen
    }
};

export { syncDatabase, syncDatabaseForDeployment };
