/**
 * Diagnostic rapide de la base de données crowdlending
 * Exécuter depuis D:\dev\crowdlending-app\backend :
 *   node diag.mjs
 */
import Database from 'better-sqlite3';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const DB_PATH = path.resolve(__dirname, 'data/crowdlending.db');

const db = new Database(DB_PATH, { readonly: true });

console.log('\n=== COMPTES PAR TABLE ===');
for (const t of ['users','investisseurs','investissements','plateformes','remboursements','simul_remboursements','depots_retraits','investissement_historique']) {
  try {
    const n = db.prepare(`SELECT COUNT(*) AS n FROM "${t}"`).get().n;
    console.log(`  ${t.padEnd(30)} ${n} lignes`);
  } catch (e) {
    console.log(`  ${t.padEnd(30)} ERREUR: ${e.message}`);
  }
}

console.log('\n=== TABLES __repair_* RESTANTES ===');
const repairTables = db.prepare("SELECT name FROM sqlite_master WHERE name LIKE '__repair_%'").all();
if (repairTables.length === 0) console.log('  (aucune)');
else repairTables.forEach(r => console.log(`  ${r.name}`));

console.log('\n=== USERS ===');
db.prepare('SELECT id, email FROM users').all().forEach(r =>
  console.log(`  user id=${r.id}  email=${r.email}`)
);

console.log('\n=== INVESTISSEURS ===');
db.prepare('SELECT id, nom, user_id FROM investisseurs').all().forEach(r =>
  console.log(`  investisseur id=${r.id}  nom="${r.nom}"  user_id=${r.user_id}`)
);

console.log('\n=== INVESTISSEMENTS (5 premiers) ===');
const invs = db.prepare('SELECT id, nom_projet, investisseur_id, statut FROM investissements LIMIT 5').all();
if (invs.length === 0) console.log('  (TABLE VIDE!)');
else invs.forEach(r =>
  console.log(`  inv id=${r.id}  investisseur_id=${r.investisseur_id}  statut=${r.statut}  projet="${r.nom_projet}"`)
);

console.log('\n=== VÉRIFICATION FK investissements → investisseurs ===');
const broken = db.prepare(`
  SELECT COUNT(*) AS n FROM investissements i
  WHERE NOT EXISTS (SELECT 1 FROM investisseurs v WHERE v.id = i.investisseur_id)
`).get().n;
console.log(broken === 0 ? '  OK (pas de FK cassée)' : `  ⚠️  ${broken} investissements avec investisseur_id introuvable!`);

console.log('\n=== VÉRIFICATION FK remboursements → investissements ===');
const broken2 = db.prepare(`
  SELECT COUNT(*) AS n FROM remboursements r
  WHERE NOT EXISTS (SELECT 1 FROM investissements i WHERE i.id = r.investissement_id)
`).get().n;
console.log(broken2 === 0 ? '  OK' : `  ⚠️  ${broken2} remboursements avec investissement_id introuvable!`);

console.log('\n=== CHECK CONSTRAINT de investissements ===');
const schemaInv = db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='investissements'").get()?.sql ?? '';
const checkLine = schemaInv.split('\n').find(l => l.includes('statut') && l.includes('CHECK'));
console.log(' ', checkLine?.trim() ?? '(non trouvé)');

console.log('\n=== RÉFÉRENCES _investissements_old RESTANTES ===');
const refs = db.prepare("SELECT type, name FROM sqlite_master WHERE sql LIKE '%_investissements_old%'").all();
if (refs.length === 0) console.log('  (aucune) ✓');
else refs.forEach(r => console.log(`  [${r.type}] ${r.name}`));

db.close();
console.log('\nDiagnostic terminé.\n');
