// initializeTaxi.js

import TaxiMapService from '../services/taxiMapService.js';
import { sequelize } from './sequelize.js';

const initializeTaxi = async () => {
    try {
        console.log('Initializing Taxi game data...');
        
        const taxiMapService = new TaxiMapService();
        
        // Stelle sicher, dass die neue Tabelle taxi_map_tile existiert (vor Zugriffen)
        try {
            await (await import('../models/taxi/taxiMapTile.js')).default.sync({ alter: true, force: false });
            console.log('✅ Tabelle taxi.taxi_map_tile ist synchronisiert');
        } catch (e) {
            console.warn('⚠️  Konnte taxi_map_tile nicht synchronisieren:', e?.message || e);
        }

        // Stelle sicher, dass die neue Tabelle taxi_map_tile_house existiert (Häuser je Ecke)
        try {
            await (await import('../models/taxi/taxiMapTileHouse.js')).default.sync({ alter: true, force: false });
            console.log('✅ Tabelle taxi.taxi_map_tile_house ist synchronisiert');
        } catch (e) {
            console.warn('⚠️  Konnte taxi_map_tile_house nicht synchronisieren:', e?.message || e);
        }

        // Stelle sicher: timestamps-Spalten in taxi_street_name vorhanden (ältere DBs hatten evtl. kein updated_at)
        try {
            await sequelize.query(`
                DO $$
                BEGIN
                    IF NOT EXISTS (
                        SELECT 1 FROM information_schema.columns 
                        WHERE table_schema = 'taxi' AND table_name = 'taxi_street_name' AND column_name = 'created_at'
                    ) THEN
                        ALTER TABLE taxi.taxi_street_name ADD COLUMN created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW();
                    END IF;
                    IF NOT EXISTS (
                        SELECT 1 FROM information_schema.columns 
                        WHERE table_schema = 'taxi' AND table_name = 'taxi_street_name' AND column_name = 'updated_at'
                    ) THEN
                        ALTER TABLE taxi.taxi_street_name ADD COLUMN updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW();
                    END IF;
                END
                $$;
            `);
            console.log('✅ timestamps-Spalten für taxi.taxi_street_name sichergestellt');
        } catch (e) {
            console.warn('⚠️  Konnte timestamps-Spalten für taxi.taxi_street_name nicht sicherstellen:', e?.message || e);
        }

        // Stelle sicher: timestamps-Spalten in taxi_map_tile_street vorhanden
        try {
            await sequelize.query(`
                DO $$
                BEGIN
                    IF NOT EXISTS (
                        SELECT 1 FROM information_schema.columns 
                        WHERE table_schema = 'taxi' AND table_name = 'taxi_map_tile_street' AND column_name = 'created_at'
                    ) THEN
                        ALTER TABLE taxi.taxi_map_tile_street ADD COLUMN created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW();
                    END IF;
                    IF NOT EXISTS (
                        SELECT 1 FROM information_schema.columns 
                        WHERE table_schema = 'taxi' AND table_name = 'taxi_map_tile_street' AND column_name = 'updated_at'
                    ) THEN
                        ALTER TABLE taxi.taxi_map_tile_street ADD COLUMN updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW();
                    END IF;
                END
                $$;
            `);
            console.log('✅ timestamps-Spalten für taxi.taxi_map_tile_street sichergestellt');
        } catch (e) {
            console.warn('⚠️  Konnte timestamps-Spalten für taxi.taxi_map_tile_street nicht sicherstellen:', e?.message || e);
        }

        // Entferne veraltete Spalte taxi.taxi_map.map_data (Übergang von JSON → relational)
        try {
            const exists = await sequelize.query(
                `SELECT EXISTS (
                    SELECT 1 FROM information_schema.columns 
                    WHERE table_schema = 'taxi' 
                      AND table_name = 'taxi_map' 
                      AND column_name = 'map_data'
                ) AS exists;`,
                { type: sequelize.QueryTypes.SELECT }
            );
            const hasColumn = Array.isArray(exists) ? (exists[0]?.exists === true || exists[0]?.exists === 't') : false;
            if (hasColumn) {
                console.log('🔧 Entferne veraltete Spalte taxi.taxi_map.map_data ...');
                await sequelize.query(`ALTER TABLE taxi.taxi_map DROP COLUMN IF EXISTS map_data;`);
                console.log('✅ Spalte map_data entfernt');
            }
        } catch (e) {
            console.warn('⚠️  Konnte Spalte map_data nicht prüfen/entfernen (nicht kritisch):', e?.message || e);
        }
        
        // Initialisiere Map-Typen
        console.log('Initializing taxi map types...');
        await taxiMapService.initializeMapTypes();
        
        // Prüfe ob bereits eine Standard-Map existiert
        const existingDefaultMap = await taxiMapService.getDefaultMap();
        if (!existingDefaultMap) {
            console.log('Creating default taxi map...');
            await taxiMapService.createDefaultMap();
        }
        
        console.log('Taxi game initialization complete.');
    } catch (error) {
        console.error('Error initializing Taxi game:', error);
        throw error;
    }
};

export default initializeTaxi;
