require('dotenv').config();
const db = require('./config/database');

async function setupBanks() {
  console.log('🏦 Configurando bancos en la base de datos...\n');

  try {
    // 1. Crear tabla de bancos si no existe
    console.log('1. Creando tabla de bancos...');
    const createBanksTable = `
      CREATE TABLE IF NOT EXISTS banks (
        id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(100) NOT NULL,
        code VARCHAR(10) UNIQUE NOT NULL,
        base_url VARCHAR(255),
        is_active BOOLEAN DEFAULT true,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `;
    await db.query(createBanksTable);
    console.log('✅ Tabla banks creada');

    // 2. Crear tabla de bank_apis si no existe
    console.log('2. Creando tabla de bank_apis...');
    const createBankApisTable = `
      CREATE TABLE IF NOT EXISTS bank_apis (
        id INT PRIMARY KEY AUTO_INCREMENT,
        bank_id INT NOT NULL,
        api_name VARCHAR(100) NOT NULL,
        endpoint VARCHAR(255) NOT NULL,
        method VARCHAR(10) NOT NULL DEFAULT 'POST',
        api_key VARCHAR(255),
        headers JSON,
        parameters_mapping JSON,
        is_active BOOLEAN DEFAULT true,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (bank_id) REFERENCES banks(id),
        UNIQUE KEY unique_bank_api (bank_id, api_name)
      )
    `;
    await db.query(createBankApisTable);
    console.log('✅ Tabla bank_apis creada');

    // 3. Insertar bancos principales de Venezuela
    console.log('3. Insertando datos de bancos...');
    
    const banks = [
      {
        name: 'Banco de Venezuela',
        code: '0102',
        base_url: 'https://bdvconciliacionqa.banvenez.com:444',
        is_active: true
      },
      {
        name: 'Banco Provincial',
        code: '0104',
        base_url: 'https://api.provincial.com',
        is_active: true
      },
      {
        name: 'Bancaribe',
        code: '0114',
        base_url: 'https://api.bancaribe.com',
        is_active: true
      },
      {
        name: 'Banco Mercantil',
        code: '0105',
        base_url: 'https://api.mercantil.com',
        is_active: true
      },
      {
        name: 'Banco Banesco',
        code: '0134',
        base_url: 'https://api.banesco.com',
        is_active: true
      },
      {
        name: 'Banco Occidental de Descuento',
        code: '0116',
        base_url: 'https://api.bod.com',
        is_active: true
      }
    ];

    for (const bank of banks) {
      // Verificar si el banco ya existe
      const checkBankSql = `SELECT id FROM banks WHERE code = ?`;
      const existingBank = await db.query(checkBankSql, [bank.code]);
      
      if (existingBank.length === 0) {
        const insertBankSql = `
          INSERT INTO banks (name, code, base_url, is_active)
          VALUES (?, ?, ?, ?)
        `;
        await db.query(insertBankSql, [bank.name, bank.code, bank.base_url, bank.is_active]);
        console.log(`✅ Banco ${bank.name} (${bank.code}) agregado`);
      } else {
        console.log(`ℹ️  Banco ${bank.name} (${bank.code}) ya existe`);
      }
    }

    // 4. Configurar APIs para Banco de Venezuela (BDV)
    console.log('\n4. Configurando APIs para Banco de Venezuela...');
    
    const bdvId = await getBankId('0102');
    
    const bdvApis = [
      {
        api_name: 'payment_reconciliation',
        endpoint: 'https://bdvconciliacionqa.banvenez.com:444/getMovement/v2',
        method: 'POST',
        api_key: '96R7T1T5J2134T5YFC2GF15SDFG4BD1Z',
        headers: JSON.stringify({
          'Content-Type': 'application/json',
          'X-API-Key': '96R7T1T5J2134T5YFC2GF15SDFG4BD1Z'
        }),
        parameters_mapping: JSON.stringify({
          "cedulaPagador": "payer_document",
          "telefonoPagador": "payer_phone", 
          "telefonoDestino": "beneficiary_phone",
          "referencia": "reference",
          "fechaPago": "payment_date",
          "importe": "amount",
          "bancoOrigen": "bank_origin",
          "reqCed": "validate_document"
        }),
        is_active: true
      },
      {
        api_name: 'movement_query',
        endpoint: 'https://bdvconciliacionqa.banvenez.com:444/apis/bdv/consulta/movimientos/v2',
        method: 'POST',
        api_key: '256D0FDD36F1B1B3F1208A9B6EC693',
        headers: JSON.stringify({
          'Content-Type': 'application/json',
          'X-API-Key': '256D0FDD36F1B1B3F1208A9B6EC693'
        }),
        parameters_mapping: JSON.stringify({
          "cuenta": "account_number",
          "fechaIni": "start_date",
          "fechaFin": "end_date", 
          "tipoMoneda": "currency",
          "nroMovimiento": "movement_number"
        }),
        is_active: true
      },
      {
        api_name: 'payment_notification',
        endpoint: '', // Se configura cuando el banco nos notifica
        method: 'POST',
        api_key: '97F6F54EF1A84F3A24FE19A3B338C77A',
        headers: JSON.stringify({
          'Content-Type': 'application/json',
          'API-KEY': '97F6F54EF1A84F3A24FE19A3B338C77A'
        }),
        parameters_mapping: JSON.stringify({}),
        is_active: true
      }
    ];

    for (const api of bdvApis) {
      const checkApiSql = `SELECT id FROM bank_apis WHERE bank_id = ? AND api_name = ?`;
      const existingApi = await db.query(checkApiSql, [bdvId, api.api_name]);
      
      if (existingApi.length === 0) {
        const insertApiSql = `
          INSERT INTO bank_apis (bank_id, api_name, endpoint, method, api_key, headers, parameters_mapping, is_active)
          VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        `;
        await db.query(insertApiSql, [
          bdvId, api.api_name, api.endpoint, api.method, 
          api.api_key, api.headers, api.parameters_mapping, api.is_active
        ]);
        console.log(`✅ API ${api.api_name} configurada para BDV`);
      } else {
        console.log(`ℹ️  API ${api.api_name} ya existe para BDV`);
      }
    }

    // 5. Configurar APIs básicas para otros bancos (ejemplo)
    console.log('\n5. Configurando APIs para otros bancos...');
    
    const otherBanks = [
      { code: '0104', name: 'Provincial' },
      { code: '0105', name: 'Mercantil' },
      { code: '0134', name: 'Banesco' }
    ];

    for (const bank of otherBanks) {
      const bankId = await getBankId(bank.code);
      
      const basicApis = [
        {
          api_name: 'payment_reconciliation',
          endpoint: `https://api.${bank.name.toLowerCase()}.com/payments/reconcile`,
          method: 'POST',
          api_key: `DEMO_KEY_${bank.code}`,
          headers: JSON.stringify({
            'Content-Type': 'application/json',
            'Authorization': `Bearer DEMO_KEY_${bank.code}`
          }),
          parameters_mapping: JSON.stringify({}),
          is_active: false // Inactivo hasta configurar
        },
        {
          api_name: 'payment_notification',
          endpoint: '',
          method: 'POST',
          api_key: `WEBHOOK_KEY_${bank.code}`,
          headers: JSON.stringify({
            'Content-Type': 'application/json'
          }),
          parameters_mapping: JSON.stringify({}),
          is_active: false
        }
      ];

      for (const api of basicApis) {
        const checkApiSql = `SELECT id FROM bank_apis WHERE bank_id = ? AND api_name = ?`;
        const existingApi = await db.query(checkApiSql, [bankId, api.api_name]);
        
        if (existingApi.length === 0) {
          const insertApiSql = `
            INSERT INTO bank_apis (bank_id, api_name, endpoint, method, api_key, headers, parameters_mapping, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
          `;
          await db.query(insertApiSql, [
            bankId, api.api_name, api.endpoint, api.method, 
            api.api_key, api.headers, api.parameters_mapping, api.is_active
          ]);
          console.log(`✅ API ${api.api_name} agregada para ${bank.name}`);
        }
      }
    }

    console.log('\n🎉 Configuración de bancos completada!');
    console.log('\n📊 Resumen:');
    console.log('   • 6 bancos configurados');
    console.log('   • BDV con 3 APIs activas');
    console.log('   • Otros bancos con configuración básica');
    console.log('\n🚀 Ya puedes usar los bancos en tu API');

  } catch (error) {
    console.error('❌ Error configurando bancos:', error);
  }
}

async function getBankId(code) {
  const sql = `SELECT id FROM banks WHERE code = ?`;
  const rows = await db.query(sql, [code]);
  return rows[0]?.id;
}

// Ejecutar si es llamado directamente
if (require.main === module) {
  setupBanks();
}

module.exports = setupBanks;