import { sequelize } from './sequelize.js';
import Match3Campaign from '../models/match3/campaign.js';
import Match3Level from '../models/match3/level.js';
import Match3Objective from '../models/match3/objective.js';
import Match3TileType from '../models/match3/tileType.js';
import Match3LevelTileType from '../models/match3/levelTileType.js';

/**
 * Initialisiert die Match3-Daten in der Datenbank
 */
async function initializeMatch3Data() {
  try {
    console.log('🎯 Initialisiere Match3-Daten...');

    // Prüfe ob bereits Daten vorhanden sind (mit Fehlerbehandlung)
    let existingCampaigns = 0;
    try {
      existingCampaigns = await Match3Campaign.count();
    } catch (error) {
      if (error.message.includes('existiert nicht') || error.message.includes('does not exist')) {
        console.log('ℹ️  Match3-Tabellen existieren noch nicht, erstelle sie...');
        existingCampaigns = 0;
      } else {
        throw error; // Andere Fehler weiterwerfen
      }
    }
    
    if (existingCampaigns > 0) {
      console.log('✅ Match3-Daten bereits vorhanden, überspringe Initialisierung');
      return;
    }

    // Erstelle Kampagne ZUERST
    console.log('🎯 Erstelle neue Kampagne...');
    const campaign = await Match3Campaign.create({
      name: 'Juwelen-Meister',
      description: 'Meistere die Kunst des Juwelen-Matchings mit einzigartigen Level-Formen',
      isActive: true
    });
    console.log('✅ Kampagne erstellt:', campaign.name);

    // Lösche existierende Level für diese Kampagne
    console.log('🔄 Lösche existierende Level...');
    await Match3Level.destroy({ where: { campaignId: campaign.id } });
    console.log('✅ Existierende Level gelöscht');

    console.log('🎯 Erstelle neue Level...');

    console.log('✅ Kampagne erstellt:', campaign.name);

    // Erstelle Level 1: Einfaches 5x5 Feld
    const level1 = await Match3Level.create({
      campaignId: campaign.id,
      name: 'Der Anfang',
      description: 'Lerne die Grundlagen mit einem einfachen 5x5 Feld',
      order: 1,
      boardLayout: 'xxxxx\nxxxxx\nxxxxx\nxxxxx\nxxxxx',
      boardWidth: 5,
      boardHeight: 5,
      tileTypes: ['gem', 'star', 'heart'],
      moveLimit: 15,
      isActive: true
    });

    // Erstelle Level 2: 7x6 Feld
    const level2 = await Match3Level.create({
      campaignId: campaign.id,
      name: 'Erste Herausforderung',
      description: 'Ein größeres 7x6 Feld stellt dich vor neue Herausforderungen',
      order: 2,
      boardLayout: 'xxxxxxx\nxxxxxxx\nxxxxxxx\nxxxxxxx\nxxxxxxx\nxxxxxxx',
      boardWidth: 7,
      boardHeight: 6,
      tileTypes: ['gem', 'star', 'heart', 'diamond'],
      moveLimit: 20,
      isActive: true
    });

    // Erstelle Level 3: L-Form mit festen Gems
    const level3 = await Match3Level.create({
      campaignId: campaign.id,
      name: 'Spielzug',
      description: 'Sei ein Profi',
      order: 3,
      boardLayout: 'xxxxx\nxooxx\nxxxgx\nxxxxx\nxxxgx',
      boardWidth: 5,
      boardHeight: 5,
      tileTypes: ['gem', 'star', 'heart', 'diamond'],
      moveLimit: 15,
      isActive: true
    });

    // Erstelle Level 4: H-Form
    const level4 = await Match3Level.create({
      campaignId: campaign.id,
      name: 'H-Form',
      description: 'Eine H-Form mit vielen Ecken und Kanten',
      order: 4,
      boardLayout: 'xxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx\nxxxxxoooxxxxx',
      boardWidth: 13,
      boardHeight: 13,
      tileTypes: ['gem', 'star', 'heart', 'diamond', 'crown', 'moon'],
      moveLimit: 30,
      isActive: true
    });

    // Erstelle Level 5: Diamant-Form
    const level5 = await Match3Level.create({
      campaignId: campaign.id,
      name: 'Diamant-Form',
      description: 'Eine elegante Diamant-Form für Fortgeschrittene',
      order: 5,
      boardLayout: 'oooxxxooo\nooxxxxxxoo\nooxxxxxxoo\nooxxxxxxoo\nooxxxxxxoo\nooxxxxxxoo\nooxxxxxxoo\nooxxxxxxoo\nooxxxxxxoo\noooxxxooo',
      boardWidth: 9,
      boardHeight: 10,
      tileTypes: ['gem', 'star', 'heart', 'diamond', 'crown', 'moon', 'star'],
      moveLimit: 35,
      isActive: true
    });

    // Erstelle Level 6: Spiral-Form
    const level6 = await Match3Level.create({
      campaignId: campaign.id,
      name: 'Spiral-Form',
      description: 'Eine komplexe Spiral-Form für Meister',
      order: 6,
      boardLayout: 'xxxxxxxxxxxxx\nxooooooooooox\nxoxxxxxxxxxox\nxoxoooooooxox\nxoxoxxxxxoxox\nxoxoxoooxoxox\nxoxoxoxoxoxox\nxoxoxoooxoxox\nxoxoxxxxxoxox\nxoxoooooooxox\nxoxxxxxxxxxox\nxooooooooooox\nxxxxxxxxxxxxx',
      boardWidth: 13,
      boardHeight: 13,
      tileTypes: ['gem', 'star', 'heart', 'diamond', 'crown', 'moon', 'star', 'crystal'],
      moveLimit: 40,
      isActive: true
    });

    console.log('✅ Alle Level erstellt');

    // Erstelle Objectives für Level 1
    await Match3Objective.bulkCreate([
      {
        levelId: level1.id,
        type: 'score',
        description: 'Sammle 150 Punkte',
        target: 150,
        operator: '>=',
        order: 1,
        isRequired: true
      },
      {
        levelId: level1.id,
        type: 'matches',
        description: 'Mache 5 Matches',
        target: 5,
        operator: '>=',
        order: 2,
        isRequired: true
      }
    ]);

    // Erstelle Objectives für Level 2
    await Match3Objective.bulkCreate([
      {
        levelId: level2.id,
        type: 'score',
        description: 'Sammle 250 Punkte',
        target: 250,
        operator: '>=',
        order: 1,
        isRequired: true
      },
      {
        levelId: level2.id,
        type: 'matches',
        description: 'Mache 8 Matches',
        target: 8,
        operator: '>=',
        order: 2,
        isRequired: true
      },
      {
        levelId: level2.id,
        type: 'moves',
        description: 'Verwende weniger als 20 Züge',
        target: 20,
        operator: '<=',
        order: 3,
        isRequired: true
      }
    ]);

    // Erstelle Objectives für Level 3
    await Match3Objective.bulkCreate([
      {
        levelId: level3.id,
        type: 'score',
        description: 'Sammle 400 Punkte',
        target: 400,
        operator: '>=',
        order: 1,
        isRequired: true
      },
      {
        levelId: level3.id,
        type: 'matches',
        description: 'Mache 12 Matches',
        target: 12,
        operator: '>=',
        order: 2,
        isRequired: true
      },
      {
        levelId: level3.id,
        type: 'moves',
        description: 'Verwende weniger als 25 Züge',
        target: 25,
        operator: '<=',
        order: 3,
        isRequired: true
      }
    ]);

    // Erstelle Objectives für Level 4
    await Match3Objective.bulkCreate([
      {
        levelId: level4.id,
        type: 'score',
        description: 'Sammle 600 Punkte',
        target: 600,
        operator: '>=',
        order: 1,
        isRequired: true
      },
      {
        levelId: level4.id,
        type: 'matches',
        description: 'Mache 15 Matches',
        target: 15,
        operator: '>=',
        order: 2,
        isRequired: true
      },
      {
        levelId: level4.id,
        type: 'moves',
        description: 'Verwende weniger als 30 Züge',
        target: 30,
        operator: '<=',
        order: 3,
        isRequired: true
      }
    ]);

    // Erstelle Objectives für Level 5
    await Match3Objective.bulkCreate([
      {
        levelId: level5.id,
        type: 'score',
        description: 'Sammle 800 Punkte',
        target: 800,
        operator: '>=',
        order: 1,
        isRequired: true
      },
      {
        levelId: level5.id,
        type: 'matches',
        description: 'Mache 18 Matches',
        target: 18,
        operator: '>=',
        order: 2,
        isRequired: true
      },
      {
        levelId: level5.id,
        type: 'moves',
        description: 'Verwende weniger als 35 Züge',
        target: 35,
        operator: '<=',
        order: 3,
        isRequired: true
      }
    ]);

    // Erstelle Objectives für Level 6
    await Match3Objective.bulkCreate([
      {
        levelId: level6.id,
        type: 'score',
        description: 'Sammle 1000 Punkte',
        target: 1000,
        operator: '>=',
        order: 1,
        isRequired: true
      },
      {
        levelId: level6.id,
        type: 'matches',
        description: 'Mache 25 Matches',
        target: 25,
        operator: '>=',
        order: 2,
        isRequired: true
      },
      {
        levelId: level6.id,
        type: 'moves',
        description: 'Verwende weniger als 40 Züge',
        target: 40,
        operator: '<=',
        order: 3,
        isRequired: true
      }
    ]);

    console.log('✅ Alle Objectives erstellt');
    console.log('🎯 Match3-Daten erfolgreich initialisiert');

  } catch (error) {
    console.error('❌ Fehler beim Initialisieren der Match3-Daten:', error);
    throw error;
  }
}

export default initializeMatch3Data;
