require('dotenv').config();
const mysql = require('mysql2/promise');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const winston = require('winston');

// Configuration du logger
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.simple(),
  transports: [
    new winston.transports.File({ filename: path.join(__dirname, '..', 'logs', 'cron_rates.log') })
  ]
});

async function updateExchangeRates() {
  logger.info('Début du script de mise à jour des taux.');

  const dbConfig = {
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME
  };

  try {
    const connection = await mysql.createConnection(dbConfig);

    const pdfUrl = 'https://www.backend-rates.bazg.admin.ch/pdf?activeSearchType=yesterday&locale=fr';
    const tempPath = path.join('/tmp', 'bazg_rates_' + Date.now() + '.pdf');

    // Télécharger le PDF
    const response = await axios.get(pdfUrl, { responseType: 'stream' });
    response.data.pipe(fs.createWriteStream(tempPath));

    // Attendre la fin du téléchargement
    await new Promise((resolve, reject) => {
      response.data.on('end', resolve);
      response.data.on('error', reject);
    });

    if (!fs.existsSync(tempPath) || fs.statSync(tempPath).size < 1000) {
      throw new Error('Fichier PDF invalide ou vide');
    }

    logger.info(`PDF téléchargé : ${fs.statSync(tempPath).size} octets`);

    // Parser le PDF (nécessite pdf-parse)
    const pdfParse = require('pdf-parse');
    const dataBuffer = fs.readFileSync(tempPath);
    const pdfData = await pdfParse(dataBuffer);

    const text = pdfData.text;
    fs.unlinkSync(tempPath);

    // Extraire les taux (même regex que PHP)
    const pattern = /([A-Z]{3})\s+.*?\s+(\d+)\s+([\d\.]+)/g;
    let matches;
    const rates = { 'CHF': 1.0 };

    while ((matches = pattern.exec(text)) !== null) {
      const code = matches[1];
      const units = parseInt(matches[2]);
      const rate = parseFloat(matches[3].replace(',', '.'));

      if (units > 0 && rate > 0) {
        rates[code] = Math.round(rate / units * 1000000) / 1000000;
      }
    }

    logger.info(`${Object.keys(rates).length} taux extraits`);

    const today = new Date().toISOString().split('T')[0];
    await connection.beginTransaction();

    const query = `
      INSERT INTO daily_exchange_rates (currency_code, rate_to_chf, rate_date, source)
      VALUES (?, ?, ?, 'BAZG_PDF')
      ON DUPLICATE KEY UPDATE rate_to_chf = VALUES(rate_to_chf), source = VALUES(source)
    `;

    for (const [currency, rate] of Object.entries(rates)) {
      await connection.execute(query, [currency, rate, today]);
    }

    await connection.commit();
    logger.info('Base de données mise à jour avec succès');

    await connection.end();
  } catch (error) {
    if (connection) await connection.rollback();
    logger.error(`ERREUR: ${error.message}`);
    process.exit(1);
  }
}

updateExchangeRates();
