import mysql from 'mysql2/promise';
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { development } from '../config.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Load .env from backend directory
dotenv.config({ path: join(__dirname, '..', '.env') });

const dbConfig = {
  host: process.env.DB_HOST || development.host || 'localhost',
  user: process.env.DB_USER || development.username || 'root',
  password: process.env.DB_PASSWORD || development.password || '',
  database: process.env.DB_NAME || development.database || 'trainingdiary',
};

async function checkDatabase() {
  let connection;
  try {
    console.log('=== Datenbank-Konfiguration ===');
    console.log('Host:', dbConfig.host);
    console.log('User:', dbConfig.user);
    console.log('Database:', dbConfig.database);
    console.log('Password:', dbConfig.password ? '***' : '(leer)');
    console.log('');
    
    connection = await mysql.createConnection({
      host: dbConfig.host,
      user: dbConfig.user,
      password: dbConfig.password,
    });
    
    // Zeige alle verfügbaren Datenbanken
    const [databases] = await connection.execute('SHOW DATABASES');
    console.log('=== Verfügbare Datenbanken ===');
    databases.forEach(db => {
      const dbName = db.Database;
      const isCurrent = dbName === dbConfig.database;
      console.log(`${isCurrent ? '→' : ' '} ${dbName}${isCurrent ? ' (VERWENDET)' : ''}`);
    });
    console.log('');
    
    // Verbinde mit der konfigurierten Datenbank
    await connection.end();
    connection = await mysql.createConnection(dbConfig);
    
    // Prüfe, ob die Tabellen existieren
    const [tables] = await connection.execute('SHOW TABLES');
    console.log(`=== Tabellen in "${dbConfig.database}" ===`);
    console.log(`Anzahl: ${tables.length}`);
    console.log('');
    
    // Prüfe spezifische Tabellen
    const tableNames = tables.map(t => Object.values(t)[0]);
    const requiredTables = [
      'training_group',
      'member_training_group',
      'club_disabled_preset_groups',
      'training_times',
      'official_tournaments',
    ];
    
    console.log('=== Prüfung wichtiger Tabellen ===');
    for (const table of requiredTables) {
      const exists = tableNames.includes(table);
      console.log(`${exists ? '✓' : '✗'} ${table}`);
    }
    console.log('');
    
    // Prüfe official_tournaments Daten
    if (tableNames.includes('official_tournaments')) {
      const [count] = await connection.execute('SELECT COUNT(*) as count FROM official_tournaments');
      console.log(`=== official_tournaments Daten ===`);
      console.log(`Anzahl Einträge: ${count[0].count}`);
      
      if (count[0].count > 0) {
        // Prüfe zuerst die Spaltennamen
        const [columns] = await connection.execute('SHOW COLUMNS FROM official_tournaments');
        console.log('Spalten in official_tournaments:');
        columns.forEach(col => {
          console.log(`  - ${col.Field} (${col.Type})`);
        });
        console.log('');
        
        const [rows] = await connection.execute('SELECT * FROM official_tournaments LIMIT 5');
        console.log('Erste Einträge:');
        rows.forEach(row => {
          console.log(`  - ID: ${row.id}, Daten:`, JSON.stringify(row, null, 2));
        });
      }
    }
    
  } catch (error) {
    console.error('Fehler:', error.message);
    if (error.code) {
      console.error('Error Code:', error.code);
    }
  } finally {
    if (connection) await connection.end();
  }
}

checkDatabase();

