const fs = require('fs');
const path = require('path');

function loadEnv() {
  const envPath = path.join(__dirname, '..', '.env');
  const envContent = fs.readFileSync(envPath, 'utf-8');
  const env = {};
  
  envContent.split('\n').forEach(line => {
    const match = line.match(/^([^=:#]+)=(.*)$/);
    if (match) {
      const key = match[1].trim();
      let value = match[2].trim();
      
      if (value.startsWith('"') && value.endsWith('"')) {
        value = value.slice(1, -1);
      } else if (value.startsWith("'") && value.endsWith("'")) {
        value = value.slice(1, -1);
      }
      
      env[key] = value;
    }
  });
  
  return env;
}

async function listLexOfficeArticles() {
  console.log('🔍 Lade LexOffice Artikel...\n');

  const env = loadEnv();
  const apiKey = env.LEXOFFICE_API_KEY;

  if (!apiKey) {
    console.error('❌ LEXOFFICE_API_KEY nicht in .env gefunden!');
    process.exit(1);
  }

  try {
    const response = await fetch('https://api.lexoffice.io/v1/articles?page=0&size=100', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Accept': 'application/json',
      },
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`LexOffice API Error: ${response.status} - ${errorText}`);
    }

    const data = await response.json();

    if (!data.content || data.content.length === 0) {
      console.log('⚠️  Keine Artikel gefunden.');
      return;
    }

    console.log(`✅ Gefunden: ${data.content.length} Artikel\n`);
    console.log('─'.repeat(80));

    data.content.forEach((article, index) => {
      console.log(`\n${index + 1}. ${article.title || article.articleNumber || 'Unbekannt'}`);
      console.log(`   ID: ${article.id}`);
      console.log(`   Artikelnummer: ${article.articleNumber || 'N/A'}`);
      console.log(`   Typ: ${article.type || 'N/A'}`);
      
      if (article.price) {
        const netAmount = article.price.netAmount || 0;
        console.log(`   Preis: ${netAmount.toFixed(2)}€ netto`);
      }
      
      if (article.description) {
        const desc = article.description.substring(0, 60);
        console.log(`   Beschreibung: ${desc}${article.description.length > 60 ? '...' : ''}`);
      }
    });

    console.log('\n' + '─'.repeat(80));
    console.log('\n💡 Kopieren Sie die IDs für Ihr Produkt-Mapping!');
    console.log('📝 Format: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n');

  } catch (error) {
    console.error('❌ Fehler:', error.message);
  }
}

listLexOfficeArticles();
